简体   繁体   中英

How do i create a script element to include jquery

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

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.
}());

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); 
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM