Venditan, The E-Commerce & Retail Experts
We're Recruiting, PHP Specialists, Enquire Here

Size Matters!

Come in and take a look inside the venditan hq!

We're recruiting php people, interested?

Show Me More

Size Matters!

Posted 26/02/2014 by Tom Walder

Small, Fast Asynchronous Deferred JavaScript


Loading & parsing Javascript is a chore for any browser - especially mobile. That's why Google PageSpeed (and any other page speed tool worth it's salt) will tell you to load Javascript last and to defer loading where possible.

This is the smallest snippet I could come up with to load your main JS file after page load.

It's a self-calling function:

<script>
(function(l,o,a,d,r){
d=l.getElementsByTagName(o)[0],r=l.createElement(o);
r.async=1;r.src=a;d.parentNode.insertBefore(r,d);
})(document,'script','/js/test.js');
</script>

 

Re-use for Loading Multiple Files


For a few extra bytes we can make the function available to re-use later.

<script>
var loadr=function(l,o,a,d,r){
d=l.getElementsByTagName(o)[0],r=l.createElement(o);
r.async=1;r.src=a;d.parentNode.insertBefore(r,d);};
loadr(document,'script','/js/test1.js');
loadr(document,'script','/js/test2.js');
</script>


I won't chastise you here for wanting to load multiple JS files - although really for production, compile and compress into one.

 

Robust?


If you believe Google and their latest Analytics snippets, then it's a pretty robust way to async load JavaScript into the page.

Back To Posts