Load jQuery Plugins Only When Required (Runtime)

I have often observed that websites that are template-driven (like blogs, cms, etc), tend to load all the required scripts and css in every page. One such example would be WordPress blogs with plugins for various types of content processing (overlay, tooltip, animation, etc.) Every page of such a WordPress driven site loads the relevant plugin stylesheets and javascripts, even though it might not be required for that particular page.

Here is a jQuery code I wrote in order to load prettyPhoto jQuery plugin (prettyPhoto homepage) only when required. This process can also be applied to other plugins by analyzing the plugin triggers from within the rest of the page content.

if(jQuery) {
   jQuery(document).ready( function() {

      // check if rel=prettyphoto exists (plugin trigger)
      if ( jQuery("a[rel^='prettyPhoto']").length > 0 ) {

         // prettyPhoto package location
         pfBaseLoc = '/wp-content/assets/prettyPhoto_compressed_2.4.3/';

         // load pretty photo css
         jQuery('<link>').attr({
            'rel': 'stylesheet',
            'type': 'text/css',
            'href': pfBaseLoc + 'css/prettyPhoto.css',
            'media': 'screen' }).appendTo(document.getElementsByTagName('head')[0]);

         // load prettyphoto js (getscript of jQuery prevents caching so using ajax)
         jQuery.ajax({
            type: 'GET',
            url: pfBaseLoc + 'js/jquery.prettyPhoto.js',
            cache: true,
            success: function() { jQuery("a[rel^='prettyPhoto']").prettyPhoto(); },
            dataType: 'script',
            data: null
         });
      }
   });

}

Note that in the above code, I did not use the handy getScript() of jQuery. This is because the getScript() function prevents caching of the JS file. That in turn may cause more server requests than needed. So, alternatively use the ajax() method to fetch script.

Web developers should actively adopt this aproach so that unneeded scripts are not loaded and consequently, page load time is reduced.

        

2 Replies to “Load jQuery Plugins Only When Required (Runtime)”

  1. The code does not work upon copy-paste. The quotation marks are all screwed up. You should use Google Prettifier to do syntax highlighting. Whatever you are using now isn’ that great.

Leave a Reply