Lazy jQuery: How to load jQuery dyamically

Ranked #968 in Education, #22,577 overall

jQuery on the fly.

jQuery is a popular javascript library with an emphasis on DOM (Document Object Model) querying and manipulation. It also was the first library to provide a cross-browser safe event which executes after the DOM is ready to be manipulated.

This lens is intended for advanced jQuery users with a rather specific need. If this isn't you, reading the lens is probably a waste of your time. The solution described in this article dynamically loads the jQuery javascript library without using ajax.

I came across the need to load jQuery based on an event after a basic html page had already loaded. This had to be done synchronously with any other code which depends on jQuery. I couldn't find a solution online that suited my needs, so thought I'd share. It's pretty simple to figure out but may save you some time.

Introduction

Why Would I Want to Load jQuery After Site my Finishes Loading?

Maybe you have a simple html page or other small file and you don't want to load jQuery the moment this file loads for whatever reason. Perhaps you want it to load faster because the jQuery functionality isn't needed most of the time. Granted, jQuery is already very small, but if you want the fastest performance possible out of a page that doesn't always invoke jQuery, but still want functionality like the $().ready() function in order to run additional code after dependencies are resolved, I believe this is the way to go.

The basic idea:

  1. Call a function that loads jQuery.

  2. Continuously poll until jQuery has loaded.

  3. Run some code that requires jQuery to be ready.

Step 1:

First let's set up an empty html document with the following in the body. When clicked, our button will load jQuery.


<html>
  <head>

  </head>
  <body>

    <div id='status'>jQuery is not loaded yet.</div>
    <input type='button' value='Click here to load it.' onclick='load()' />

  </body>
</html>

Step 2:

The following code loads jQuery when a user clicks the button we created earlier. We're basically implementing jQuery's own $.getScript function since jQuery isn't available yet.


<script>

load = function() {
  load.getScript("jquery-1.2.6.js");
  load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
}

// dynamically load any javascript file.
load.getScript = function(filename) {
  var script = document.createElement('script')
  script.setAttribute("type","text/javascript")
  script.setAttribute("src", filename)
  if (typeof script!="undefined")
  document.getElementsByTagName("head")[0].appendChild(script)
}

</script>

Step 3:

Here's the function called by step 2. It simply checks for jQuery every 200 milliseconds until found. When found, you can execute code which requires jQuery.
If jQuery isn't found after 5 seconds of trying, this function times out and stops trying.


load.tryReady = function(time_elapsed) {
  // Continually polls to see if jQuery is loaded.
  if (typeof $ == "undefined") { // if jQuery isn't loaded yet...
    if (time_elapsed <= 5000) { // and we havn't given up trying...
      setTimeout("load.tryReady(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
    } else {
      alert("Timed out while loading jQuery.")
    }
  } else {
    // Any code to run after jQuery loads goes here!
    // for example:
    $("#status").css({
    'font-size':'20px',
   'color':'green'}).text("jQuery is loaded and ready to go!");
  }
}



Now your page will load faster than ever since it only loads jQuery when needed!

Click here to open the whole demo in one page.

Questions or Comments? Let Me Know!

submit

by

echo85

A programmer who's learning about javascript, jQuery and lenses today.

Feeling creative? Create a Lens!