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
- var jq = document.createElement('script');
- jq.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js';
- jq.onload = function () { initJQuery(); };
- var h = document.getElementsByTagName('head')[0];
- 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
- //============================================
- //Begin Dynamically load jQuery
-
- if (typeof jQuery == 'undefined') {
- //var jq = document.createElement('script');
- //jq.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js';
- //jq.onload = function () { initJQuery(); };
- //var h = document.getElementsByTagName('head')[0];
- //h.appendChild(jq);
- //http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet/
- (function () {
- // more or less stolen form jquery core and adapted by paul irish
- function getScript(url, success) {
- var script = document.createElement('script');
- script.src = url;
- var head = document.getElementsByTagName('head')[0],
- done = false;
- // Attach handlers for all browsers
- script.onload = script.onreadystatechange = function () {
- if (!done && (!this.readyState
- || this.readyState == 'loaded'
- || this.readyState == 'complete')) {
- done = true;
- success();
- script.onload = script.onreadystatechange = null;
- head.removeChild(script);
- }
- };
- head.appendChild(script);
- }
-
- getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js', initJQuery);
- })();
- }
- else {
- initJQuery();
- }
-
- //End ofDynamically load jQuery
- //============================================
And Voila! Problem Solved!
Technorati Tags:
Dynamically Load jQuery,
Unobtrusive JavaScript Library,
Code,
onload,
IE8, and IE7 Windows Live Tags:
Dynamically Load jQuery,
Unobtrusive JavaScript Library,
onload,
IE8, and IE7,
Code