Search code examples
javascriptjqueryfunctionasynchronouspage-load-time

Calling functions when needed


So in my page I have some little scripts which I dont really need to load once you visit the site and in fact the user might not need them at all in their entire session.

Also, according to this: http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS its not a good practise either.

So for example, currently I have everything in 'When dom ready':

$(function() {
 // most of the code of which is not needed
});

If I dont place the code inside the Dom ready, its not executable at most of the times. So I thought of doing seperate functions for each snippet.

For exmaple:

function snippet1() {
   // Code here
}

and then when I need that snippet, I load it when needed with mouseclick. (Not always a mouselcick, depends what I need to load).

For example:

$('#button1').click(function() {
  snippet1();
});

So my question is: Is this the way of loading functions async so you reduce the page load time or is there a better way? I havent read this anywhere my examples, I just thought of it.

Note that I am aware of the asynch loading's but that is not my option here, since I could combine all the functions in just one js file which will be cached, so page load time will be less than loading every time asynch js files.


Solution

  • You're mixing several things:

    1. Page load time
    2. JavaScript parsing time - After the script is loaded, it has to be parsed (error checking, compiling to byte code, etc)
    3. Function execution time

    You can't do much about the page load time since you don't want to split the script. You may consider to split it into two parts: One which you always need and an "optional" part which is rarely needed. Load the rare functions in the background.

    Note that page load times become pretty moot after the site has been visited once and you've made sure the browser can cache the files.

    If you want to reduce parse times, you have two options:

    1. Don't load parts that you don't need.
    2. Compress the scripts. Google has a great tool for that: the Closure Compiler. Besides making your scripts faster, it will also check for many common mistakes.

    The last part is the execution times. These are only relevant if the functions are called at all and when they do a lot. In your case, I guess you can ignore this point.