1

I must include jQuery in a page using code:

if (typeof window.jQuery === "undefined") {
    document.write('<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"><\/script>');
    if (typeof Prototype !== "undefined") {
        document.write('<script>jQuery.noConflict();<\/script>');
    }
}

But then if I try to use jQuery, Firebug logs "jQuery undefined".

jQuery(document).ready(function() {
    //
});

but jquery is correctly loaded

jQuery

mcont
  • 1,463
  • 1
  • 18
  • 29

3 Answers3

3

I would suggest against using document.write, use dom manipulation.

if (typeof window.jQuery === "undefined") {
    var script = document.createElement('script');
    script.onload = function(){
        if (typeof Prototype !== "undefined") {
            jQuery.noConflict();
        }
    }
    script.src = 'http://code.jquery.com/jquery-latest.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);   
}

http://jsfiddle.net/ALCDr/

Musa
  • 89,286
  • 16
  • 105
  • 123
  • I just tried and that doesn't work. I think as long he is getting script from external resource he need to use `window.onload` as in Rob answer – Peter Sep 01 '12 at 20:15
  • @Musa [checked, still not working..](http://codepad.org/iksxQImB). However it's nice that works to OP :) – Peter Sep 01 '12 at 20:32
  • @PeterSzymkowski the script needs time to load, that's why that's why the check for Prototype is in the onload function – Musa Sep 01 '12 at 20:35
1
window.onload = function() {
  jQuery(document).ready(function() {
    alert('!');
  });
}

do the trick.

Peter
  • 15,758
  • 7
  • 46
  • 76
1

The way the HTML5 boilerplate does it is the most efficient way.

<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.0.min.js"><\/script>')</script>

This will check to see if jQuery has been defined yet (I.e loaded), or (if not) it will load write the script to the page :).

Alexander Wigmore
  • 2,975
  • 4
  • 32
  • 57