Delay in loading external JavaScript file

Previously we have learned how to delay in executing JavaScript code from this post – How to delay in loading JavaScript code?.

We used setTimeout() JavaScript window method for delay loading our JavaScript code. Now, in this tutorial, we are going to see how to delay in loading an external JavaScript file using the same JavaScript window setTimeout method that we used previously.

Now let’s see our JavaScript code:

setTimeout(load_js, 4000); // Delay 4 seconds in loading function

function load_js()
{
    // Get the head tag
    var head_ID = document.getElementsByTagName("head")[0]; 
    // Create script element       
    var script_element = document.createElement('script');
    // Set the script type to JavaScript
    script_element.type = 'text/javascript';
    // External JS file
    script_element.src = 'http:/www.domain.com/script.js';
    head_ID.appendChild(script_element);
}

In the above code, we have set the external JavaScript file into our HTML head tag in our function and then call the function with setTimeout() JavaScript method. We have set the time for 4000 milliseconds or 4 seconds to load our function 4 seconds delay after window load. So our javaScript file will delay 4 seconds in loading after the window load.

How to delay in loading JavaScript code?

How to disable your website accessing from iframe using JavaScript?

We can also write our code like this:

setTimeout(function() {
    // Get the head tag
    var head_ID = document.getElementsByTagName("head")[0]; 
    // Create script element       
    var script_element = document.createElement('script');
    // Set the script type to JavaScript
    script_element.type = 'text/javascript';
    // External JS file
    script_element.src = 'http:/www.domain.com/script.js';
    head_ID.appendChild(script_element);

}, 4000);


So we have successfully able to delay in loading our external JavaScript code.

One response to “Delay in loading external JavaScript file”

  1. Chris says:

    Take a bow my man, this worked a treat for an external widget I had. When I ran a test in page insights after dropping this top script in the speed was as if the script never existed and then it loaded a treat – set it for 6 seconds.

    Thanks

    C

Leave a Reply

Your email address will not be published. Required fields are marked *