Handling Multiple Scripts on Web Page
Introduction
This article shows how to handle multiple scripts on web page. Actually the traditional mechanism for registering even handlers through JavaScript is to assign a function to the DOM (Document Object Model) element's corresponding attribute.
This article shows how to handle multiple scripts on web page. Actually the traditional mechanism for registering even handlers through JavaScript is to assign a function to the DOM (Document Object Model) element's corresponding attribute.
For example,
suppose we had a function:
function
doStuff() {
document.writeln("my test line");
}
Now, we could
then either assign it within our HTML markup:
<body onload="doStuff();">
</body>
Or, we could
assign it from within JavaScript code:~
window.onload =
doStuff();
Here is the complete
design:
Both approaches
will cause the function to execute when the page is loaded. But the advantage
of the second is that the behavior is more cleanly separated from the markup.
This strategy
works quite well with one function. Let's suppose we have another function:
function
doStuff() {
document.writeln("my test line");
}
function
doAnotherStuff() {
document.writeln("my another test line");
}
Now, we could
then attempt to assign this function to run on page load:
window.onload =
doStuff() + doAnotherStuff();
OR
window.onload =
doStuff();
window.onload =
doAnotherStuff();
Here is the
complete design:
Works well so
far, but this assignment actually trumps the first one. The .onload attribute
can only store one function reference at a time. So, we can't add this to the
existing behavior.
Now, at this
situation $(document).ready() mechanism handles this gracefully. Each call to
the method adds the new function to an internal queue of behaviors; when the
page is loaded all of the functions will execute. The functions will run in the
order in which they were registered on page.
Here is the
complete design:
I hope you like
it. Thanks.
Comments
Post a Comment