0

Im trying to write a script that will append the jquery cdn script to the body of the document.

function addJquery() {
    url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);
}
addJquery();

What am i doing wrong here

2
  • 4
    All the spaces on the far right between j and s won't help you Commented Oct 16, 2013 at 23:27
  • Sorry that was i typo. Commented Oct 17, 2013 at 3:13

2 Answers 2

4

You can't add scripts to the body and have them execute. Late-loaded scripts must be loaded through the head element:

(function addJQuery() {
  var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
  var script = document.createElement('script');
  script.url = url;
  script.onload = function() { addJQuery(); }
  document.head.appendChild(script);
}());

However, this loads jQuery regardless of whether it's already loaded, so that's no good. Here's what you generally want instead:

(function loadMyCode() {
  // do we have jquery? if not, load it.
  if (typeof jQuery === "undefined") {
    var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
    var script = document.createElement('script');
    script.url = url;
    script.onload = function() {
       // this will run after jquery gets loaded
       loadMyCode();
    }
    document.head.appendChild(script);
    return;
  }

  // if we get here, we know we have jquery
  //
  // rest of the code goes here.
}());
Sign up to request clarification or add additional context in comments.

Comments

0

This is another way

(function () { 
var li = document.createElement('script'); 
li.type = 'text/javascript'; 
li.src= "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
li.async=true;
var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(li, s); 
})();

3 Comments

What is the safest fastest and most fail-proof way to incorperate jquery.
Should i not use Googles CDN, i understand this to be a best practice.
It completely depends upon network's speed..you cant guaruntee it, that the js will load each time you request it..There can be many possibilities for js file not to be loaded i.e. if user's network speed is slow, or he losts the connectivity..Its always a good practice to use CDN...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.