Wednesday, October 23, 2013

Supercharge your pagespeed with Minified CSS and Deferred loading of JS

I'm a server side junkie, no doubt. I'm always trimming my bytes no matter how minimal the gain and I love picking up milliseconds of load time here and there...It really ads up. Being so wrapped up in the internals of my work I sometimes forget about the big wins to be had optimizing client side code. So, here's a quick snippet on how to speed up your website with two easy methods...

1. Minify and Cache CSS - minify for php

Download the minify code and unzip it to the root directory of your site and follow the user guide to complete the install (it's very easy!).

Then you're ready to start minifying...

CSS Include
<link rel="stylesheet" type="text/css" href="/min?f=path/to/file_one.css,path/to/file_two.css,path/to/file_three.css" />

It's really that simple!!

2. Defer Loading of JS - standard JS implementation (recommended by google)
Deferred JS Code
<script type="text/javascript">
  function downloadJSAtOnload() {
    var js_files = [];
    //add files here
    js_files.push('/my/file/one.js');
    js_files.push('/my/file/two.js');
    js_files.push('/my/file/three.js');
    //end adding files
    for(var key in js_files){ 
      var element = document.createElement("script");
      element.src = js_files[key];
      document.body.appendChild(element);
    }
  }
  if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>


If you're having trouble using the deferred loading of JS you can also use the minify method with your js as follows:
JS Include
<script type="text/javascript" src="/min?f=path/to/file_one.js,path/to/file_two.js,path/to/file_three.js" />


I hope your ready to see your site load faster than ever, I sure am.

Please comment, share and follow!

No comments:

Post a Comment

Have a question? Something to add to the post? Do it here...