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


i loading js external source right before </body> tag. experimenting see happens if server hangs while trying serve third party js. seems on page works fine, browser still spins though page still loading. there way load javascript in such way browser won't wait on declare page loaded?

for reference, have tried following 2 methods load 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> 

an answer compiled comments above , own experimentation:

if load third party js after rest of page has finished loading, browser render page though loaded, if external resource hangs. 1 way accomplish load js within window.settimeout timeout greater page's standard load time.

when loading external js through js function rather through standard script tag, remember if have data- attributes, belong in resource.dataset object.

so, in 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 5000 timeout works me because page loads in under 5 seconds, , don't need js loading in first 5 seconds. if need yours sooner or page takes longer load, need adjust number. also, @adeneo mentioned above, way accomplish same thing load js through ajax later.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -