1

I want to include the jquery file dynamically when I need to it.
But there is a problem, the error message that appear $ is not defined

What I done:

// include the file dynamically.
var parent, script;
parent = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = "text/javascript";
script.src = "includes/jquery.js";
parent.appendChild(script);

// The usage
$('#box').remove();
Lion King
  • 32,851
  • 25
  • 81
  • 143

3 Answers3

1

Handle onload event to make sure your script is loaded before you use it

script.onload = function () { $('#box').remove() }
parent.appendChild(script);
Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
1

For IE, I think you need to use the onreadystatechange callback. E.g.

script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState == 'loaded' ||
    script.readyState == 'complete') {
  $('#box').remove();
}
};
Kiran
  • 1,708
  • 1
  • 11
  • 14
0

try this:

(function () {

function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("includes/jquery.js", function () {

     //jQuery loaded
     console.log('jquery loaded');
     $('#box').remove();

});


})();
Muthu
  • 1,022
  • 1
  • 7
  • 17