kat February 2016

JS loaded asynchronously in body keeps browser in "loading" mode

I am loading some JS from an external source right before my </body> tag. I am experimenting to see what happens if the server hangs while trying to serve this third party JS. It seems that everything on my page works just fine, but the browser still spins as though the page is still loading. Is there a way to load this javascript in such a way that the browser won't wait on it to declare the page fully loaded?

For reference, I have tried the following two methods to load my JS asynchronously:

<script>
  var resource = document.createElement('script');
  resource.src = "https://myserver.com/js/myjs.js”;
  var script = document.getElementsByTagName('script')[0];
  script.parentNode.insertBefore(resource, script);
</script>

and

<script async src="https://myserver.com/js/myjs.js"></script>

Answers


Arun Sharma February 2016

You can load js by getscript, check this demo


kat February 2016

An answer compiled from the comments above and my own experimentation:

If you load the third party JS after the rest of the page has finished loading, then the browser will render the page as though it is completely loaded, even if the external resource hangs. One way to accomplish this is to load the JS within a window.setTimeout with a timeout greater than your page's standard load time.

When you are loading external JS through a JS function rather than through a standard script tag, remember that if you have any data- attributes, they belong in the resource.dataset object.

So, in the example above,

 <script async data-my-data="someData" src="https://myserver.com/js/myjs.js"></script>

becomes

<script>
    window.setTimeout(function () {
        var resource = document.createElement('script');
        resource.dataset.myData = "someData";
        resource.src = "https://myserver.com/js/myjs.js";
        var script = document.getElementsByTagName('script')[0];
        script.parentNode.insertBefore(resource, script);
    }, 5000);
</script>

Note that 5000 as a timeout works for me because my page loads in well under 5 seconds, and I don't need the JS that I am loading in the first 5 seconds. If you need yours sooner or your page takes longer to load, you will need to adjust this number. Also, as @adeneo mentioned above, another way to accomplish the same thing would be to load the js through ajax later.

Post Status

Asked in February 2016
Viewed 2,716 times
Voted 8
Answered 2 times

Search




Leave an answer