DOMContentLoaded event provides this functionality, but isn’t supported in older browsers.
runOnLoad is a tiny standalone function that provides this functionality, with a size of only 278 bytes when minified and 225 bytes when minified and gzipped.
Download one of the files below and either incorporate it into your code or serve it as a separate file.
|runOnLoad.js||278 bytes||Minified version|
|runOnLoad.src.js||1,338 bytes||Full version, with comments|
Tasks are added by passing them to the function:
1 2 3 4 5 6 7
Tasks can be added at any time.
If a task is added after the content has loaded then it will be run asynchronously as soon as possible.
(This means code immediately following a call to
runOnLoad is guaranteed to run before the task passed to
runOnLoad, regardless of whether the content has already loaded.)
The function listens for two events, and runs the tasks as soon as one of the events fires.
In browsers that support the standard
addEventListener function (browsers other than Internet Explorer 8 or lower) the function listens for the
DOMContentLoaded event fires in browsers more recent than Chrome 0.2, Firefox 1.0, Internet Explorer 9, Safari 3.1, and Opera 9.0.
load event fires in all browsers, but only once all external files have loaded.
In browsers that only support the
attachEvent function (Internet Explorer 8 or lower) the function listens for the
load event fires in all versions, but only once all external files have loaded.
load event to fire in older browsers.
The standard version of runOnLoad does not make use of these tricks, as these browsers are increasingly rare and the function is intended to be as small as possible.
Internet Explorer 8
In some cases it is important to provide an enhanced experience for Internet Explorer 8 users (such as in corporate networks running Windows XP, which does not support more recent versions of Internet Explorer).
The files below contain an extended version of runOnLoad that also listens for the
readystatechange event in Interner Explorer 8.
This allows Internet Explorer 8 to run the tasks without waiting for all external files to be loaded.
|runOnLoad-readystatechange.js||349 bytes||Minified version|
|runOnLoad-readystatechange.src.js||1,586 bytes||Full version, with comments|