3

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?

6
  • 1
    Why do you add the script tag dynamically? Commented Feb 13, 2015 at 3:05
  • How do you conclude jquery is not working? Commented Feb 13, 2015 at 3:05
  • This sounds like a race condition. The code above loads jQuery asynchronously so, you won't be able to access jQuery until it downloads and loads. Commented Feb 13, 2015 at 3:06
  • the .js file is using a simile $(document).click(function(){ alert('works'); }); I have that same code in both the js file (loaded in the footer) and the html file in the body. the console error i'm getting is "$ is not defined" Commented Feb 13, 2015 at 3:15
  • did you try using jQuery instead of $ ?? Commented Feb 13, 2015 at 3:19

3 Answers 3

2

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;
}  
Sign up to request clarification or add additional context in comments.

1 Comment

Nailed it! Thanks jdp!
0

Your jQuery code is not working may be caused by jQuery is not loaded yet while browser executing your jQuery code. Use function below to dynamically load jQuery with callback. Put your jQuery code inside a callback function.

function loadScript(url, callback) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = url;

    if (typeof(callback) === 'function') {
        s.onload = s.onreadystatechange = function(event) {
            event = event || window.event;
            if (event.type === "load" || (/loaded|complete/.test(s.readyState))) {
                s.onload = s.onreadystatechange = null;
                callback();
            }
        };
    }

    document.body.appendChild(s);
}

/* Load up jQuery */
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function() {
    // Put your jQuery code here.
});

Comments

-1

You need to include jQuery inside the HTML code. jQuery won't work for you because your script is loaded before jQuery is loaded.

1 Comment

Completely false - scripts can be dynamically loaded in pages.

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.