I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload
on the <body>
tag.
I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload
on the <body>
tag.
I think http://code.google.com/p/domready/ is exactly what you're looking for.
If you are ever writing your own JavaScript file that cannot depend on the existing libraries out there and would like to execute only after the page is loaded, this library is for you.
Simply do this:
<html lang="en">
<head>
<script src="domready.js" type="application/javascript"></script>
<script type="application/javascript">
DomReady.ready(function() {
alert('dom is ready');
});
</script>
</head>
<body>
</body>
</html>
Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.
Here is the code:
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);