最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Two Javascript functions one window.onload = Custom.init; and one window.onload = function() { - Stack Overflow

programmeradmin4浏览0评论

I'm using two functions one is from this site / and its using function call like this:

window.onload = Custom.init;

and after that I'm using another function call like this

window.onload = function() {...

The second one is killing first one! How can I modifie or make different call on second one so they can work together?

I'm using two functions one is from this site http://ryanfait./resources/custom-checkboxes-and-radio-buttons/ and its using function call like this:

window.onload = Custom.init;

and after that I'm using another function call like this

window.onload = function() {...

The second one is killing first one! How can I modifie or make different call on second one so they can work together?

Share Improve this question asked Mar 26, 2012 at 16:06 munge83munge83 1531 gold badge4 silver badges19 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

Use addEventListener/attachEvent. You can use a library that abstracts this, like jQuery:

$(window).load(function () {
  // run code
});

This can be run multiple times with different functions without issues.

window.onload = function() {
    Custom.init();
    // ...
};

You'll have to create your own function which calls them both.

window.onload = function(){
    Custom.init();
    function() { ... }
}

My preference for this is:

loadFunctions = [];
window.onload = function() {var x; while(x = loadFunctions.shift()) x();};

Then, instead of setting window.onload, I do:

loadFunctions.push(function() {...});

Of course, I can do this because I'm not using external libraries which may interfere with window.onload.

EDIT: If you don't have control over one of them, you could do this:

var ool = window.onload;
window.onload = function() {
    if( ool) ool();
    // new code here
};

Manually call Custom.init ?

window.onload = function() {
   Custom.init();
   //your stuff
};

How about a nice little wrapper for all onLoad event handler?

window.onLoadHandlers = [];
window.onLoad = function() {
    while (window.onLoadHandlers.length) {
        window.onLoadHandlers.shift()();
    }
};

Then just push the two functions to that array:

window.onLoadHandlers.push( Custom.init );
window.onLoadHandlers.push( function() { ...

You may though consider using jQuery or any other library that provides a better solution for this.

发布评论

评论列表(0)

  1. 暂无评论