Search code examples
jqueryoptimizationfooter

jquery-in-footer code optimization (theory)


I'm using various jquery plugins, including lazy-load, scrollTo, an image effect thing, and various snippets collected from reading people's posts on this site. Now, all of these effects get fired off, from footer, and there's like a lag that's happening. The effects are like, hesitant, or jumpy, or unsmooth.

I've played around with using document ready vs. window load, and I have a snippet in header to prevent FOUC, but I have a feeling there is like a queueing problem, or memory overload or something. (It's like when you try to use your laptop with too many programs running, and everything feels heavy and slow.)

Especially in Opera. For some reason it's like Opera can't handle my site.

It doesn't make sense to me that a few jquery effects should pose such a problem. People play intense videogames, no problem, and yet a website with a fadeIn effect is suddenly too much for computers to handle? There must be something I'm doing wrong with my footer code.

So onto my theory question -

Is there like a standard practice I need to start following, to make sure all of these jquery effects run smoother, gobble up less memory, don't conflict with each other, or whatever?


Solution

  • Well first you need to figure out whether it's your JavaScript/jQuery code that's slowing down the web page or if it's the plugins'. In other words, profile your code.

    Once you have done that, you can start optimizing. There are tons of articles out there that discuss optimizing jQuery.

    Some tips:

    • ID selectors by themselves are fast since they are delegated to getElementById(), which is heavily optimized by the browser.
    • Cache jQuery selectors. That is, don't call $('.class1 #id2 > child3') 10 times in a row. Save it on a variable like var $mytd

    If the fault lies in the plugin, your options are more limited. But there are some things you can try:

    • Make sure they are minified so that they load quickly (it doesn't just take time to transfer the files, but also to read since they are not compiled)
    • Find lightweight alternatives. e.g. If you just need a fade effect, don't include a full blown 50 kb jQuery library.

    Opera should be very fast, at least from what I hear. However if you are testing using IE, expect it to be slow. Their JavaScript engine just isn't very good.