Generally speaking, window.onload is enough. If we want to load multiple events, we can take the following approach:
window.onload = function(){
func1();
func2();
func3();
// More loading events………………
}
But if due to some special needs, we can’t write them together? For example, if the current area is for administrators, when the page is generated in the background, this part of the page will only be generated when the user is an administrator, and this part also uses some special scripts. The above method is useless!
//Backend code
<%# The following script is prepared for administrators%>
<% if @user.role == "manager" %>
window. onload = function(){
func1();
func2();
//Load confidential script...
}
<% end %>
The page generated in this case has two window.onload code blocks. Obviously, the second one overwrites the first one. At this time, it is the turn of the loadEvent function to appear.
var loadEvent = function(fn) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = fn;
}else {
window.onload = function() {
oldonload();
fn();
}
}
}
It perfectly solves the problem of mutual coverage. The usage is as follows:
loadEvent(func1);
loadEvent(func2);
loadEvent(func3);
//More loading events
But the real problems are always so unexpected and tricky. Recently, I want to put all functions into a closure to avoid naming conflicts, such as the famous $ DOM selector. JQuery, Prototype, and mootool all use it as the name of the selector, and coexistence has become a serious problem.
(function(){
if(!window .JS){
window['JS'] = {}
}
var onReady = function(fn){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = fn;
}else {
window.onload = function() {
oldonload();
fn();
}
}
}
JS.onReady = onReady;
var $ = function(id){
return document.getElementById(id);
}
JS.$ = $;
})()
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn