Thursday, April 10, 2014 #

Dynamically Load jQuery From Unobtrusive JavaScript Library

I am tasked with dynamically injecting jQuery into each page if it is not already loaded from an Unobtrusive JavaScript Library.

The normal way of injecting a script tag would be:

Code Snippet
  1. var jq = document.createElement('script');
  2. jq.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js';
  3. jq.onload = function () { initJQuery(); };
  4. var h = document.getElementsByTagName('head')[0];
  5. h.appendChild(jq);

 

However, this will never work on IE8 or IE7, because the .onload callback is never called.

So what is the [workaround]?

 

Code Snippet
  1. //============================================
  2. //Begin Dynamically load jQuery
  3.  
  4. if (typeof jQuery == 'undefined') {
  5.     //var jq = document.createElement('script');
  6.     //jq.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js';
  7.     //jq.onload = function () { initJQuery(); };
  8.     //var h = document.getElementsByTagName('head')[0];
  9.     //h.appendChild(jq);
  10.     //http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet/
  11.         (function () {
  12.             // more or less stolen form jquery core and adapted by paul irish
  13.             function getScript(url, success) {
  14.                 var script = document.createElement('script');
  15.                 script.src = url;
  16.                 var head = document.getElementsByTagName('head')[0],
  17.                     done = false;
  18.                 // Attach handlers for all browsers
  19.                 script.onload = script.onreadystatechange = function () {
  20.                     if (!done && (!this.readyState
  21.                          || this.readyState == 'loaded'
  22.                          || this.readyState == 'complete')) {
  23.                         done = true;
  24.                         success();
  25.                         script.onload = script.onreadystatechange = null;
  26.                         head.removeChild(script);
  27.                     }
  28.                 };
  29.                 head.appendChild(script);
  30.             }
  31.  
  32.             getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js', initJQuery);
  33.         })();
  34. }
  35. else {
  36.     initJQuery();
  37. }
  38.  
  39. //End ofDynamically load jQuery
  40. //============================================

And Voila!  Problem Solved!

Technorati Tags: ,,,, Windows Live Tags: Dynamically Load jQuery,Unobtrusive JavaScript Library,onload,IE8, and IE7,Code

Posted On Thursday, April 10, 2014 1:33 AM | Comments (0)

Copyright © intermark

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski