jQuery in Action
182
CHAPTER 6
jQuery utility functions
file dynamically. The page is shown in listing 6.5 and can be found in the file
chapter6/$.getScript.html.
chapter6/$.getScript.html.
<html>
<head>
<title>$.getScript Example</title>
<link rel="stylesheet" type="text/css" href="../common.css">
<script type="text/javascript"
src="../scripts/jquery-1.2.1.js"></script>
<script type="text/javascript">
$(function(){
$('#loadButton').click(function(){
$.getScript(
'new.stuff.js'//,function(){$('#inspectButton').click()}
);
});
$('#inspectButton').click(function(){
someFunction(someVariable);
});
});
</script>
</head>
<body>
<button type="button" id="loadButton">Load</button>
<button type="button" id="inspectButton">Inspect</button>
</body>
</html>
This page defines two buttons
d
that we use to trigger the activity of the exam-
ple. The first button, labeled Load, causes the new.stuff.js file to be dynamically
loaded through use of the
loaded through use of the
$.getScript()
function
b
. Note that, initially, the sec-
ond parameter (the callback) is commented out--we'll get to that in a moment.
On clicking that button, the new.stuff.js file is loaded, and its content is evalu-
ated. As expected, the inline statement within the file triggers an alert message as
shown in figure 6.6.
shown in figure 6.6.
Clicking the Inspect button executes its
click
handler
c
, which executes the
dynamically loaded
someFunction()
function passing the value of the dynamically
loaded
someVariable
variable. If the alert appears as shown in figure 6.7, we know
that both the variable and function are loaded correctly.
If you'd like to observe the behavior of Safari that we warned you about ear-
lier, make a copy of the
HTML
file of listing 6.5, and uncomment the callback
Listing 6.5 Dynamically loading a script file and examining the results
Fetches the script on
clicking the Load button
clicking the Load button
b
Displays result on clicking
the Inspect button
the Inspect button
c
Defines the
buttons
buttons
d