Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting jquery into js file

I have a js file that in which i want to include jquery. in order to include the jquery script i am using this clode:

    var script = document.createElement('script');
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);

this works, I can see that incuded the script correctly. My inspector shows that it loaded the script but jquery wont work.

any ideas?

like image 569
Johnathon Pfleger Avatar asked Dec 10 '25 05:12

Johnathon Pfleger


1 Answers

You need to make sure the script you are dynamically loading is actually loaded before attempting to use it.

To do so, use script.onload to fire a callback once the load is completed.

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head') [0].appendChild(script);
script.onload = function () {
  /* jquery dependent code here */
  console.log($);
};

MDN has an example that's more adaptable to a callback you specify -

// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#Dynamically_importing_scripts
function loadError (oError) {
  throw new URIError("The script " + oError.target.src + " is not accessible.");
}

function importScript (sSrc, fOnload) {
  var oScript = document.createElement("script");
  oScript.type = "text\/javascript";
  oScript.onerror = loadError;
  if (fOnload) { oScript.onload = fOnload; }
  document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
  oScript.src = sSrc;
}  
like image 143
jdphenix Avatar answered Dec 11 '25 19:12

jdphenix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!