O'Reilly logo

jQuery Essentials by Troy Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loading and executing JavaScript – getScript()

Most of the Ajax methods get some kind of data from the server. The .getScript() method is different. It retrieves JavaScript from the server, parses, and then executes it. Like the other Ajax methods, it returns a promise, but in this case the success function is not passed any data.

// load and run javascript
$('#get-javascript').click(function (event) {
    $.getScript('script.js').then(function () {
        alert("getScript() was successful.");
    }, function(err){
        alert('ERROR:' + JSON.stringify(err));
    });
});

The code that the .getScript() method loaded is still available after it executes, but there is no easy way to call the code again unless you keep a reference to it. In the example code, we assign the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required