JS loaded asynchronously in body keeps browser in "loading" mode
For reference, I have tried the following two methods to load my JS asynchronously:
var resource = document.createElement('script');
resource.src = "https://myserver.com/js/myjs.js”;
var script = document.getElementsByTagName('script');
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.
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.
Asked in February 2016Viewed 2,716 timesVoted 8Answered 2 times