jQuery in Action
Dynamically loading scripts
181
Under its covers, this function uses jQuery's built-in Ajax mechanisms to fetch the
script file. We'll be covering these Ajax facilities in great detail in chapter 8, but
we don't need to know anything about Ajax to use this function.
script file. We'll be covering these Ajax facilities in great detail in chapter 8, but
we don't need to know anything about Ajax to use this function.
After fetching, the script in the file is evaluated; any inline script is executed,
and any defined variables or functions become available.
WARNING
In Safari, the script definitions loaded from the fetched file don't become
available right away, even in the callback to the function. Any dynamically
loaded script elements don't became available until after the script block
within which it is loaded relinquishes control back to the browser. If your
pages are going to support Safari, plan accordingly!
available right away, even in the callback to the function. Any dynamically
loaded script elements don't became available until after the script block
within which it is loaded relinquishes control back to the browser. If your
pages are going to support Safari, plan accordingly!
Let's see this in action. Consider the following script file (available in chapter6/
new.stuff.js):
new.stuff.js):
alert("I'm inline!");
var someVariable = 'Value of someVariable';
function someFunction(value) {
alert(value);
}
This trivial script file contains an inline statement (which issues an alert that
leaves no doubt as to when the statement gets executed), a variable declaration,
and a declaration for a function that issues an alert containing whatever value
is passed to it when executed. Now let's write a page to include this script
leaves no doubt as to when the statement gets executed), a variable declaration,
and a declaration for a function that issues an alert containing whatever value
is passed to it when executed. Now let's write a page to include this script
Function syntax: $.getScript
$.getScript(url,callback)
Fetches the script specified by the url parameter using a GET request to the specified
server, optionally invoking a callback upon success.
server, optionally invoking a callback upon success.
Parameters
url
(String) The URL of the script file to fetch.
callback
(Function) An optional function invoked after the script resource has been
loaded and evaluated.
The following parameters are passed:
loaded and evaluated.
The following parameters are passed:
The text loaded from the resource
The string success
Returns
The XHR instance used to fetch the script.
The XHR instance used to fetch the script.