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

5
  • Yes.. it is in the head section Commented Sep 1, 2012 at 20:05
  • The code is in a external javascript file included with <script> Commented Sep 1, 2012 at 20:07
  • Are you using jQuery after it's loaded or before? Commented Sep 1, 2012 at 20:10
  • Please read this and this - these days document.write is really mad function, giving you unexpected results Commented Sep 1, 2012 at 20:10
  • After... see this jsfiddle jsfiddle.net/pampurio97/B7dq2 Commented Sep 1, 2012 at 20:10

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

3 Comments

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
@Musa checked, still not working... However it's nice that works to OP :)
@PeterSzymkowski the script needs time to load, that's why that's why the check for Prototype is in the onload function
1
window.onload = function() {
  jQuery(document).ready(function() {
    alert('!');
  });
}

do the trick.

Comments

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 :).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.