Dynamically Include JQuery Plugins

When you are building a website that has dynamic content (coming from a CMS for example) it is not possible to know what content will be on a given page.

Some pages will have photos, some will have tables and some may have another form of control or interaction that requires manipulation via JQuery or styling with CSS.

To keep page size to a minimum it makes sense to only load the plugin code required by the individual page.

The way to do this is to use the includeMany jQuery plugin to include plugins on page load. Once the external file has been loaded it triggers an event which applies the plugin effect to the page.


Sounds simple right?... introduce Internet Explorer 8

Everything was working smoothly, on my pages where the lightbox was required (any image that has a rel=lightbox) then the lightbox javascript and css are included and applied, thus:

if($('a[rel=lightbox]').length > 0) {
    $.include(siteId + '/scripts/lightbox/lightbox.css');
    $.include(siteId + '/scripts/lightbox/lightbox.js', applyLightBox);
}

Notice the applyLightBox function to call when load is complete

function applyLightBox() {
    $('a[rel=lightbox]').lightBox();
}

 

The above concept works well but was not working in Internet Explorer 8 (except in compatibility view). I had a tinker round inside of the includeMany script and found (after a debugging with some alert boxes) that the URL it wwas attempting to use was being injected into the <script> src attribute as [object] and not as a string (some/path.js)

The fix was to append to a blank string to force the URL (which IE8 was treating as an object) be converted to a string.

The result looking like this:

js.setAttribute('src','' + url);

Dynamically Include JQuery Plugins

I develop and maintain complex websites that often make use of JQuery technology for improved usability.
There are so many useful plugins but not every page requires them all. Rather than slow down the site by loading all the script libraries every time it is possible to dynamically include those that are required for the current page.
For example, only include the lightbox plugin for pages where there are images that will make use of it.
Sounds simple right... well it should have been.
November 10, 2009