Javascript Performance: How to include your code

Most beginning SEO/performance books will tell you that you should not include javascript in the head of your html but rather at the end of the page. This is because every time javascript code is found, it blocks the entire time while it downloads the code and then executes. The problem is even at the bottom of the page it blocks making the browser lag, or become glitchy until everything has been downloaded and processed.

The solution is to use javascript to load the javascript into your page, you can right a small amount of code that will download your javascript in the background without blocking. This means that your javascript will start downloading even while the browser is working on downloading bigger items like images and not stop the browser from working on other items, this will improve load times on your page and make for a better user experience. The script I am showing below gives you the ability to provide a callback function to run once your code is downloaded. You can put this code anywhere in the page though if you put it at the bottom you will not even need to wrap your code in “window.load() {}” to avoid errors.

Here is some example code:

<script type="text/javascript">
  function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState) { //IE
      script.onreadystatechange = function(){
        if (script.readyState == "loaded" || script.readyState == "complete"){
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function(){
      callback();
      };
    }

    script.src = url;
    document.getElementByTagName("head")[0].appendChild(script);
  }

  loadScript("myapp.js", function(){
    Application.init();
  });

</script>

Checkout a few libraries that will do this for you as well:

* LazyLoad library

* The LABjs library

This entry was posted in JavaScript, Web Development. Bookmark the permalink.

Leave a Reply