Proper use of javascript window.onload event

I have this loop code to reduce 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 was shown that if the code runs before the DOM completes, 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 as not to move the script code to the bottom of the page. But that doesn't seem to work, because it seems like the array loop is running until the DOM completes.

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

In addition, I tried to remove "var" to delete the area without changing.

+4
source share
4 answers

You can also try this approach without using the 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

+2
source

If you can use jquery, you can use a ready-to-listen document:

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

http://www.jquery.com

as per the comment above, you tried:

 if (document.readyState === "complete") { init(); } // call whatever function u want. 
0
source

It is better to use the function without preliminary scanning dom to create a cache, preliminary scanning is not required when you use a simple function with building a cache. Using jQuery you can create such a function (your own javascript method below):

 window.__jcache = {}; window.$jc = function(u) // jQuery cache { if( u == undefined ) { return window.jQuery; } if( typeof u == 'object' || typeof u == 'function' ) { return window.jQuery(u); } if( window.__jcache[u] == undefined ) { window.__jcache[u] = window.jQuery(u); } return window.__jcache[u]; }; 

Or no frame (native javascript):

 window.__domcache = {}; window.getObj = function(u) // jQuery cache { if( u == undefined ) { return null; } if( typeof u == 'object' || typeof u == 'function' ) { return u; } if( window.__domcache[u] == undefined ) { window.__domcache[u] = document.getElementById(u); } return window.__domcache[u]; }; 

So you can do:

 var o = $jc('a1'); // for jquery version var o = getObj('a1'); // The native javascript method (jamex) 

This is a trick.

Greetz, Erwin Haantjes

0
source

The load event is fired at the end of the document loading process. At this point, all the objects in the document are in the DOM, and all the images and subframes have finished loading.

MDN - window.onload

I think you are trying to call code outside of onload. See this fiddle

0
source

All Articles