0

I am trying to load a js link after 5 second page load . when my page load then js link work.

My link is

<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script>

when page is load then after 5 second this link will be work.

3 Answers3

1

You can use something like this using promises:

// Make a function to return a promise for the sleep duration
function sleep(ms)
{
    return new Promise(resolve => setTimeout(resolve, ms));
}

// make a function to handle the sleep
async function loadNewScript(seconds, src)
{
    await sleep(seconds * 1000);   // This is 5 seconds (time in miliseconds)
    getScript(src);   
}

// make a function to get the script
function getScript(src)
{
    return new Promise(function (resolve, reject)
    {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}

// And then just call it on pageload (this is not full page load, only DOM)
document.addEventListener("DOMContentLoaded", function()
{
   // loadNewScript(seconds, src)
   loadNewScript(5, "http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js");
});
Ivan86
  • 5,597
  • 2
  • 11
  • 30
0

You might want to use the defer option in your script tag.

<script defer src="..."></script>

With this option the script downloading/execution won't interfere with the html parsing.

Here you can see another options.

Arnold Gandarillas
  • 3,279
  • 24
  • 35
0

You can add a script element in the DOM. Take a look here.

Waht you can do is insert the script element with a setTimeout:

setTimeout(function(){
    var script = document.createElement('script');
    script.onload = function () {
        //do stuff when the script is loaded
    };
    script.src = "//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js";
    document.head.appendChild(script); //or something of the likes
}, 5000);