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 267 bytes when minified and 219 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||267 bytes||Minified version|
|runOnLoad.src.js||1,330 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 Internet 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,578 bytes||Full version, with comments|
Using runOnLoad as a wrapper
In code where the
runOnLoad function is only called once, it is more efficient to use a modified version to wrap the code.
The modified version is also smaller, and does not create the
runOnLoad global variable.
To use runOnLoad as a wrapper, download one of the files below and replace the underscore near the end of code with your own code.
|runOnLoad-wrapper.js||193 bytes||Standard version|
|runOnLoad-wrapper-readystatechange.js||276 bytes||Version with readystatechange|