Utilize JavaScript to load an external script at the bottom of the body for improved website performance

On my website, I am utilizing the Mobile ESP script to determine whether visitors are accessing it from a mobile device or desktop. Depending on the type of device, I dynamically load the necessary scripts and CSS stylesheets for optimal navigation.

However, I am facing an issue where I need to load a script at the bottom of the body tag for it to function correctly. Is there a method to achieve this?

<head>
    <script type="text/javascript">
    if (MobileEsp.isTierIphone || MobileEsp.isTierTablet || MobileEsp.isMobilePhone) {
        var cssUrl = "css/mobilePortraitStyle.css";
            $(document.head).append(
              $("<link/>")
              .attr({
                rel:  "stylesheet",
                type: "text/css",
                media: "screen and (orientation:portrait)",
                href: cssUrl
              })
            );
        var cssUrl = "css/mobileLandscapeStyle.css";
            $(document.head).append(
              $("<link/>")
              .attr({
                rel:  "stylesheet",
                type: "text/css",
                media: "screen and (orientation:landscape)",
                href: cssUrl
              })
            );
    } 

    else {
        var cssUrl = "css/desktopStyle.css";
            $(document.head).append(
              $("<link/>")
              .attr({
                rel:  "stylesheet",
                type: "text/css",
                href: cssUrl
              })
            );
        var jsUrl = "js/skrollr.min.js";
            $(document.head).append(
              $("<script/>")
              .attr({
                src: jsUrl
              })
            );
    }
    </script>

Answer №1

Give this a shot, it will attach the scripts to the end of your body tag

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is an external Javascript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("body")[0].appendChild(fileref)
}

Utilize it like this

loadjscssfile("myscript.js", "js") //dynamically load and append this .js file
loadjscssfile("mystyle.css", "css") //dynamically load and append this .css file

insert this after the body tag

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Issue in Babel: The preset 'latest' could not be located in the directory even though it was installed globally

I executed a global installation of Babel using: npm install -g babel-cli npm install -g babel-preset-latest Although it is generally not recommended to install Babel globally, I find it preferable in order to maintain a clean directory structure without ...

What is the best way to navigate and map through an array of objects, especially when encountering an empty object?

I am currently in the process of developing a bootleg version of Amazon with a focus on creating the Questions & Answers component. The issue I have encountered is that in my dummyData, there are instances where a product may not have any questions, lead ...

Exporting JSON blend files in Three.js is causing an error that says "Cannot read property 'type' of undefined."

Trying to display the default 3D cube template from Blender v2.74 in Chrome browser, I exported it as json using the threejs v1.4.0 add-on and I'm using Three.js revision 71. Referencing the documentation at , I attempted to load this json model stor ...

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...

JavaScript updates the cursor after the completion of the JS function

Here is some code that I have been working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> </head> <body style="background-color:yellow;width ...

html code abruptly halted due to an unexpected termination of the file

I'm experiencing an issue with my senaraiperalatanstaf.php file. I inserted some PHP code in between, but now I'm getting a parse error indicating an unexpected end of the file. I've tried troubleshooting it without success. Any help would b ...

Interact with the horizontal click and drag scroller to navigate through various sections effortlessly, each designed to assist you

Currently, I am facing an issue with my horizontal scrolling feature in JavaScript. It works perfectly for one specific section that has a particular classname, but it fails to replicate the same effects for other sections that share the same classname. ...

What is the speed of retrieving new data once it has been inserted into a firebase real-time database?

In the midst of developing my personal project using next.js, I've encountered an issue with a component that includes a getstaticprops function. This function scrapes a website and then posts the extracted data to a firebase realtime database. Howeve ...

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Switching between light and dark mode in R Shiny tables with customizable headings

I'm currently working on a visualization project for tracking Covid-19 data, and I'm having trouble changing the text color above and below a table I've created. I've attached an image to show exactly what needs to be modified. Additio ...

Prevent selection of future dates in JavaScript by using the user's chosen StartDate

Here is the code I currently have: var today = new Date().toISOString().split('T')[0]; document.getElementsByName("StartDate")[0].setAttribute('min', today); $('#StartDate').change(function myfunction() { var endDate = ...

Can you explain the meaning of -ms-value?

I recently came across a solution for an issue specific to IE, and it worked perfectly for me. You can find the solution here: Change IE background color on unopened, focused select box However, I'm still puzzled about the meaning of -ms-value. Any i ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

The error message "Potree-Core: THREE is undefined" indicates that the

I'm currently developing a web-based application that can be used offline by other users on their local machines. Within my NPM project, I am utilizing Potree-Core, which relies on THREE.js. However, the source code does not include an import for THR ...

An exception known as NullPointerException arises when attempting to invoke JDBC within a servlet

While running my RegistrationServlet, I encountered an issue when trying to create a Database object. Below is the servlet code snippet: @WebServlet("/register") public class RegistrationServlet extends HttpServlet { private static final long serial ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

Utilize HTML to resize image to fit within container

I've encountered an issue while working with Adobe Dreamweaver CS5. I added a swap behavior to an image in an html document, expecting it to pop up at its original size and restore on mouse out. However, the swapped image ends up filling the entire sc ...

What are the steps to configure MongoDB on Heroku using MongoHQ and Node.js?

I am currently using a local application, which is what I'm most familiar with. Heroku provided the following snippet of code: var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || &apos ...