jJavascript window.onload event correct usage

27,767

You could also try this approach without using a framework:

window.onload = (function(){
    return function(){
        var aarr = [];
        for (var z=1; z<=10; z++) {
            aarr.push(document.getElementById("a"+z));
               alert(aarr[z-1].id);
        }
     };
})();

JSFiddle

Share:
27,767
Jamex
Author by

Jamex

Updated on July 14, 2022

Comments

  • Jamex
    Jamex almost 2 years

    I have this loop code to reduce the DOM calls in my Javascript, and reuse them.

    aarr = [];
    
    for (var z=1; z<=10; z++) {
        c = z-1;
        aarr[c] = document.getElementById("a"+z); 
    }
    

    I have been shown that if the code is ran before the DOM is complete, then the array is null. Moving the script after the last html code will work.

    So now I want to put this code inside the window.onload event so to not have to move the script code to the bottom of the page. But it apparently does not work because it appears that the array loop is executed before the DOM is completed.

    window.onload=function(){
    
        var aarr = [];
        for (var z=1; z<=10; z++) {
            c = z-1;
            aarr[c] = document.getElementById("a"+z);
        }
    }
    

    Also, I have tried to remove the "var" to remove scope without making a difference.

  • Jamex
    Jamex over 12 years
    Thanks Rick, I am not using jquery, so this won't work for me.
  • Jamex
    Jamex over 12 years
    Thanks, I read that post before and I actually am getting this to work for firefox with that code, unfortunately, IE versions are all giving me errors. I am walking through the script line by line.
  • Jamex
    Jamex over 12 years
    Thanks Erwin, are these jquery code? I don't know/have jquery.
  • Richard A
    Richard A over 12 years
    Hey jamex.i made some changes to ur loop and it works fine for me..see the fiddle added :)
  • Jamex
    Jamex over 12 years
    Thanks Richard, I will give it a try.
  • Codebeat
    Codebeat over 12 years
    The second code is the non-jQuery version, the getObj function
  • Codebeat
    Codebeat over 12 years
    below the line "Or without a framework (native javascript):" is yours
  • Saxoier
    Saxoier over 12 years
    @Richard Aikoroje: Next time fork the fiddle. In addition: (function(){})(); is useless. The only thing you achieve is that you expand the [[scope]].