Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple javascript window.onload solution

Tags:

javascript

Before i ask this question, i never post about questions like this but I don't understand how to implement it in my code. i have code like this

window.onload = function() {
 var url  = getQueryVariable("url");
 document.getElementById('view').src = url;
}
window.onload = function() {
    var linkDirect = document.getElementsByClassName("frame");
    for (var i = 0; i < linkDirect.length; i++) {
        linkDirect[i].href = "http://namablog.blogspot.com/p/demo.html?url=" + linkDirect[i].href
    }
}

then, how can I make the code execution using only one window.onload

like image 746
Zhinto Avatar asked May 09 '13 14:05

Zhinto


3 Answers

You can use addEventListener or any jQuery equivalent.

window.addEventListener('load', function (){
    alert('Function #1');
});

window.addEventListener('load', function (){
    alert('Function #2');
});

Be sure to call these before the window is loaded.

like image 183
Bart Avatar answered Sep 19 '22 08:09

Bart


window.addEventListener will not work in IE so use window.attachEvent

You can do something like this

function fun1(){
    // do something
}

function fun2(){
    // do something
}


var addFunctionOnWindowLoad = function(callback){
      if(window.addEventListener){
          window.addEventListener('load',callback,false);
      }else{
          window.attachEvent('onload',callback);
      }
}

addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
like image 20
rohit verma Avatar answered Sep 19 '22 08:09

rohit verma


Just my 2 cents, My personal fav way of doing this is as follows:

function window_onload(cb) {
    try {
        if (typeof cb == 'function') {
            if (document.readyState == 'complete') cb();
            else if (window.hasOwnProperty('jQuery')) jQuery(window).on('load', cb);
            else if (window['addEventListener']) document.addEventListener('load', cb, false);
            else if (window['attachEvent']) {
                //  iFrame
                if (window['frameElement']) document.attachEvent('onreadystatechange', function(){ if (document.readyState === 'complete') window_onload(cb); });
                else window.attachEvent('onload', cb);
            }
            else {
                var fn = window.onload; // very old browser, copy old onload
                window.onload = function() { fn && fn(); ready(); };
            }
        }
    }
    catch (err) { if (window['console'] && console['error']) console.error("ERROR[window_onload()]", err); }
    return window;
}

This pretty much covers just about everything. What little (mainly extremely old browsers I suppose?) it doesn't cover, you could easily debug, if needed. This also goes ahead and launches the callback if the document is already 'loaded'.

like image 39
SpYk3HH Avatar answered Sep 22 '22 08:09

SpYk3HH