If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
I have been looking for a script like this for awhile because the window.onload() does not handle load events as I had planned. The browser will render everything in order and your onload script will run once it gets to that point when the DOM reaches it. So, in order for something to load at the exact moment when the DOM recognizes it, regardless of where it’s at in the rendering of the entire page, you can use this script.
I decided to play around with this since the example provided below does not show why you want to use this.
The following snippet will render a segment of text even though the images before it have yet to render.
function doLoad() {
//without this if statement 'Element Ready' will be displayed twice
if (arguments.callee.done) return;
arguments.callee.done = true;
var text = document.createTextNode("Element Ready!");
var message = document.getElementById("message");
message.appendChild(text);
message.style.backgroundColor = '#296C97';
message.style.Color = '#FFFFFF';
}
var er={
ceasePoll:function(){
clearTimeout(er.poll);
},
startPoll:function(){
var me = this;
er.poll = setTimeout(function(){er.chkDomId()},50)
},
cleanUp:function(callback) {
er.ceasePoll();
callback();
},
chkDomId:function(elId,callback) {
if (elId) er.elId = elId;
if (callback) er.callback = callback;
if (document.getElementById && setTimeout) {
var el = document.getElementById(er.elId);
if (el) {
er.cleanUp(er.callback);
} else {
er.startPoll(er.elId,er.callback);
}
}
}
}
er.chkDomId('message', doLoad);
window.onload = function(){er.cleanUp(doLoad)};
View this here.
Now, your saying … cool but what is it really doing?
Well if you take a look at the exact same page without the onload callback, you will see that the ‘Element Ready’ does not appear until the pages are done rendering. View this here.
And I did one more with basically a pre-loaded image in case wanted to render an image with your text when it becomes available to the DOM. View this here. For this one, there’s a small change in the code:
function doLoad() {
//without this if statement 'Element Ready'
//will be displayed twice
if (arguments.callee.done) return;
arguments.callee.done = true;
var text = '
This image as loaded with the callback.’;
var message = document.getElementById(”message”);
message.innerHTML = text;
message.style.backgroundColor = ‘#296C97′;
message.style.Color = ‘#FFFFFF’;
}
Check out the article by Muffin Research Labs here.
If you enjoyed this post, make sure you subscribe to my RSS feed!
RSS feed for comments on this post · TrackBack URI
Leave a reply