coderanger.com blog news about what I am developing and other random thoughts
Javascript cool feature of the day: on Browser Ready
From:
http://www.fearthecowboy.com/2007/02/javascript-cool-feature-of-day-on.html
A nice little one-liner script you can use in your HMTL page to run some a function when the browser is done loading the HTML.
I have been using this cool little snippet for a while, something I factored down for my own purposes, and tucked away in my little bag of tricks. I didn’t realize that others’ were not using something similar to this, (I saw a spate of posts where people were using document.write)[SHUDDER!]. So, I’m going to post it, and let the world rejoice:
var _my_init = document.addEventListener ? document.addEventListener("DOMContentLoaded", function(){myinit();}, false): setInterval( function(){if (/loaded|complete/.test( document.readyState )){ clearInterval(_my_init);myinit(); } }, 10);
Works in IE, FireFox, and Safari. Probably others, as I think most browsers support one of the two methods for bootstrapping an init function.
To use it, just replace the two myinit() calls with whatever you want to run, and the replace the _my_init variables to something that’ll be unique to you. I’d comment on my crazy desire to overload the living tar out of the ternary operator in javascript, but that’d be redundant.
This entry was posted on Sunday, July 8th, 2007 at 10:00 pm and is filed under General.
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.