jquery and javascript: two load functions?
hey guys,
quick question: is it actually possible and semantic to use two $(window).load(function(e){
functions on one website?
e.g. i have a header.php which holds a &l开发者_如何转开发t;script>
tag with some jquery - $(window).load(function(e){
is part of it. underneath it i have another tag that links to an external .js file that has the again a $(window).load(function(e){
.
is this allowed and ok?
thank you!
Yes. Every load()
declaration you make will simply be appended to the existing handler.
From the docs on .bind()
(which is the function that handles the actual work for the load()
shortcut):
When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.
The .load()
function (and other event-related functions) accepts a function that it places in the event handler queue when the event fires.
So, to more directly answer your question, yes.
Lets just talked about how is it possible?
Suppose, you have more than one events which you want to call on when your page completely loaded. Lets examine this in JavaScript
to get more about the concept and keep it simple to easy to understand.
var pageLoadEvents = [];
We have created an array where we will keep all our event which we want to call when page loaded.
pageLoadEvents.push( function() {
alert("hello!");
} )
And:
pageLoadEvents.push( function() {
alert("How are you doing?");
} )
Now, you have defined all your events that you would like to raise on page load and all of them are in a pageLoadEvents
array. Here, we write our final piece:
window.onload = function() {
for(var index=0; index<pageLoadEvents.length; index++) {
pageLoadEvents[index]();
}
}
All events that we keep in pageLoadEvents
array will be executed one by one.
Every time you call a load
on $(window)
it keep the content (e.g function(e) { .. }) you defined in load
in an array and finally execute them each of them.
精彩评论