Ajax Utility Functions

The other high-level jQuery Ajax utilities are functions, not methods, and they are invoked directly through jQuery or $, not on a jQuery object. jQuery.getScript() loads and executes files of JavaScript code. jQuery.getJSON() loads a URL, parses it as JSON, and passes the resulting object to the specified callback. Both of these functions call jQuery.get(), which is a more general purpose URL-fetching function. Finally, jQuery.post() works just like jQuery.get() but performs an HTTP POST request instead of a GET. Like the load() method, all of these functions are asynchronous: they return to their caller before anything is loaded, and they notify you of the results by invoking a callback function that you specify.

jQuery.getScript()

The jQuery.getScript() function takes the URL of a file of JavaScript code as its first argument. It asynchronously loads and then executes that code in the global scope. It can work for both same-origin and cross-origin scripts:

// Dynamically load a script from some other server
jQuery.getScript("http://example.com/js/widget.js");

You can pass a callback function as the second argument, and if you do, jQuery will invoke that function once after the code has been loaded and executed:

// Load a library and use it once it loads
jQuery.getScript("js/jquery.my_plugin.js", function() {
    $('div').my_plugin();  // Use the library we loaded
});

jQuery.getScript() normally uses an XMLHttpRequest object to fetch the text of the script to be ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.