JS loaded asynchronously in the body saves the browser in boot mode

I load JS from an external source right before the </body> . I am experimenting to find out what happens if the server freezes while trying to service this third-party JS. Everything seems to be working fine on my page, but the browser is still spinning, as if the page is still loading. Is there a way to load this javascript in such a way that the browser will not wait to declare the page fully loaded?

For reference, I 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> 
+7
javascript html asynchronous script-tag
source share
2 answers

The answer, made up of the comments above and my own experiments:

If you load third-party JS after the rest of the page has finished loading, the browser will display the page as if it was fully loaded, even if the external resource freezes. One way to achieve this is to load JS within window.setTimeout with a timeout that exceeds the standard page load time.

When you load external JS through a JS function, and not through a standard script tag, remember that if you have data- attributes, they belong to 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> 

Please note that 5000 as a timeout works for me because my page loads in less than 5 seconds and I don't need the JS that I load in the first 5 seconds. If you need yours earlier or your page takes longer to load, you will need to adjust this number. Also, as mentioned above, described above, another way to accomplish the same thing is to load js via ajax later.

0
source share

You can load js using getscript , check this demo

-4
source share

All Articles