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 (v开发者_运维知识库ar 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.
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
If you can use jquery, then you can use the document ready listener:
$(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, have you tried:
if (document.readyState === "complete") { init(); } // call whatever function u want.
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
MDN - window.onload
I guess you try calling code outside of onload. See this fiddle
Better to use a function without pre-scanning the dom to create a cache, Pre-scanning is not needed when you use a simple function with a cache construction. With jQuery you can can create a function like this (native javascript method below this):
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 without a framework (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)
That does the trick.
Greetz, Erwin Haantjes
精彩评论