Oct
23
2011

Use jQuery and Modernizr to load javascript conditionally, based on existence of DOM element

In the past year or so, Modernizr has really exploded on the web development scene. It allows the detection of browser abilities, such as geolocation, canvas, etc. Version 2 also merged with yepnope.js which allows for the conditional loading of CSS & JS. If you don’t know what Modernizr is, their site provides lots of clear documentation to show you its’ power. The one thing that wasn’t clear to me, was if I could load things conditionally based on the existence of a DOM element. Turns out you can, as long as you write your own custom test. Luckily, it turned out to be pretty easy.

The goods in action

Go straight to Demo page, or download the Zip. Note: The demo doesn’t really show much. In order to see what’s happening, look at the Net tab within Firebug (or the Network tab in Chrome’s Developer Tools etc), and you’ll see jQuery UI load in only if the ‘promo’ div exists.

How it all works

Modernizr lets you test for a ton of functionality, but in order to test for a specific DOM element, you need to use the addTest() plugin API. My goal was to write a test to find a specific div, then if that div is found, load in a piece of javascript. In a real world scenario, imagine a toolbar like Gigya/ShareThis/AddThis which only loads on article pages. You could detect if the main ‘article’ div existed, then load in the script. This prevents the script from loading when you don’t need it. Or if you had some large fancy promo that needed jQuery UI. No need for your users to load that whole code library unless they need to, right?

So once your page is loading jQuery and Modernizr, this is what that test would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(document).ready(function() {

  /*####
  Load in script only when DOM element exists, and use callback function
  ####*/


  Modernizr.addTest('mycustomtest', $('.promo').length > 0);

  Modernizr.load({
    test: Modernizr.mycustomtest,
    yep: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js',
    callback: function () {
      //Run this when the 'mycustomtest' condition is met
      $('.promo').append('<br />I detected the "promo" class, loading in jQuery UI');
    }
  });

});

The code is all sitting within a standard jQuery document.ready function. This just makes sure that everything in the DOM (all HTML elements) are actually loaded on the page, so that our test will actually have a correct result.

The Modernizr.addTest line adds in a new test called ‘mycustomtest’, and the test itself uses jQuery to see if the ‘promo’ class exists. If it does (‘yep’), it loads in jQuery UI. Then the callback function runs whatever you want. In this case, I’m just outputting a message. All tests must be for a yes/no value, but as long as it adheres to that rule, you can test for whatever you want.

So there it is. I never want to load in huge chunks of javascript when I don’t have to. So with this custom Modernizr test, and a little jQuery, I check for a DOM element, and only load something when I need it. This can be used in a lot of ways, so it’s up to you to see if it will be of any benefit. Also, you can do this all without jQuery, but you would have to put the Modernizr custom test at the very bottom of your page, so that the DOM elements above it load in before it runs.

Related Posts

About the Author:

I like technology, sci-fi, fantasy, and anime. You know, cool geeky stuff.

3 Comments + Add Comment

  • Hi
    I try your method, but I wonder why its said
    uncaught Reference Error: $ is not defined

    • You need to include jquery file. Make sure you had included that…

  • Nice Post. Tested, worked fine. But i need to think of a different concept, instead of checking for a classname exists, i need to load a js on click of a button, I will think of that, Kindly also provide me the script. It will be useful for the readers.

Leave a comment