Lazy Load Resources Based on Element Presence

By  on  

Fans of AMD JavaScript will probably tell you that they love loading only what they need, when they need them.  I am one of those people.  Let's take a site like mine for example: some pages require a syntax highlighter, some do not.  Why make the effort to load the syntax highlighter CSS and JavaScript if there are no pre elements that would require it?

The following is an example of how I occasionally load resources based on DOM contents:

$('article pre').length && (function() {
        var mediaPath = '/assets/';

        $('').attr({
            type: 'text/css',
            rel: 'stylesheet',
            href: mediaPath + 'css/syntax.css'
        }).appendTo(document.head);

        var syntaxScript = document.createElement('script');
        syntaxScript.async = 'true';
        syntaxScript.src = mediaPath + 'js/syntax.js';
        document.body.appendChild(syntaxScript);
    })();

The arguments against this practice will be (1) concatenating into existing JS and CSS to save on the number of requests and (2) flash of content style changes.  The first argument needs to be judged on a per-case basis;  if the required CSS and JS is small, it should be concatenated to a file used throughout the site or site subsection.  The second argument can always be hushed with a bit of transition magic!

Recent Features

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    Basic AJAX Requests Using MooTools 1.2

    AJAX has become a huge part of the modern web and that wont change in the foreseeable future. MooTools has made AJAX so simple that a rookie developer can get their dynamic pages working in no time. Step 1: The XHTML Here we define two links...

  • By
    HTML5 download Attribute

    I tend to get caught up on the JavaScript side of the HTML5 revolution, and can you blame me?  HTML5 gives us awesome "big" stuff like WebSockets, Web Workers, History, Storage and little helpers like the Element classList collection.  There are, however, smaller features in...

Discussion

  1. Really interesting and surprisingly simple, I need to look into this for an upcoming build, thanks for sharing.

  2. Does async make a difference when the script is being injected dynamically (like in the code above)? I thought it only applies on “pre-existing” script elements (i.e. scripts that appear in the HTML source of the page).

    • Hm, that question is quite old, but it looks like that async = true is not needed.

  3. The first argument is why I would concatenate this; the difference in load time for this particular functionality would be imperceptible and would ensure the functionality is available whether syntax highlighting is used down the page or on a separate one.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!