Monday, February 13, 2012

Lazy load jQuery plugins when you need them

One big problem I notice with big huge projects is that your lists of CSS and JavaScript includes sometimes become several lines long, and often can be included on every single page if you are integrating into a CMS.

There are several methods of including plugins only when you need them. I'll touch briefly on two and demonstrate a third that I found and modified.

Require.js
Require.js is a module loader that will include the files you specify and then run a block of code after they are done loading. It's more geared towards making web applications than websites, and can be compared to #include statements in C or C++. The idea behind it is to reduce HTTP calls to dependencies and build more optimized code.



Yepnope
Yepnope is a module loader that is conditional. You test for things like Modernizr tests, which check for web browser features, and you can also prefix things with ie! to make them only load in IE browsers.



Now I will demonstrate the use of a loader plugin for jQuery that I made a small modification to.

Lazy.js
Lazy is a jQuery plugin that will only load jQuery plugins if they are executed.

However, the plugin in its original form would load other plugins once they were used, regardless if the jQuery selector was actually being used. The modification I made only loaded the plugin if there was at least one or more elements being returned by the jQuery selector.

The benefit of this is that you can have a single script.js file with multiple jQuery plugins being used at once, and the only ones that will load are the ones that are being executed, and only the ones that actually affect elements on the page.

[NOT COMPLETE]

http://requirejs.org
http://net.tutsplus.com/tutorials/javascript-ajax/easy-script-loading-with-yepnope-js/
http://unwrongest.com/projects/lazy/

No comments:

Post a Comment