Create non blocking javascript

Posted by Andi Syahputra | 12:00 PM
I have a trick for you to manage your webpage's javascript for faster page loading. Usually, browser loading javascript sequentially that cause it must wait for javascript to load complete, one by one.
This technique will load javascript while the webpage load, is called asynchronous javascript a.k.a non-blocking javascript. Now, I'll show you how to load your javascript as asynchronous one... :D

Non blocking script technique will use javascript to load javascript. Seems confusing?
This is how we embed javascript as usual:
<script src='javascript.js'></script>

Now here is the non-blocking version. You can put it into <head> or <body> tag:
<script type='text/javascript'>
(function(){var s=document.createElement('script');s.async="async";s.type="text/javascript";s.src='javascript.js';var h=document.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})();
</script>

So, whether the javascript is not loading (timeout) then the webpage and other element will still loading without have to wait that script to load complete.

To compare both techniques, you can use simple javascript alert("test");
Normal version: When alert function fired, the webpage won't load complete until we click OK to close alert box
Non-blocking version: The webpage will continue loading although the alert function fired and alert box still appear.
hi folks, visit my other tutorial blog at Kumpulan tutorial menarik
0 comments