Running javascript code on page load, without using the onload tag
How can I run a JavaScript code when the 开发者_开发百科page loads without using the onload
tag?
I'm trying to run this script:
<script type="text/javascript">
function displayLightbox() {
document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
}
</script>
That displays a lightbox.
Like this:
window.onload = function WindowLoad(event) {
alert("Page is loaded");
}
Edit: if some other code is also using window.onload
after that script then it will be "overwritten" - to make sure it's executed (and abort any other onload
) put it in the bottom of the page.
Edit 2: On second thought, you better add onload listener instead of overwriting it:
<script type="text/javascript">
if (window.addEventListener) { // Mozilla, Netscape, Firefox
window.addEventListener('load', WindowLoad, false);
} else if (window.attachEvent) { // IE
window.attachEvent('onload', WindowLoad);
}
function WindowLoad(event) {
alert("Another onload script");
}
</script>
This will prevent any conflicts with existing code and is more cross browser as far as I can tell.
Live test case is available here: http://jsfiddle.net/yahavbr/GZPTG/ tested for IE8, Chrome and Firefox (latest versions) feel free to test for more.
maybe put a javascript code at the end of the page just before the closing </body>
tag.
.
.
.
<script>
yourFunctionHere();
</script>
</body>
You can do
<head>
<script>
document.onload = function() { /*run code here */}
</script>
</head>
A cleaner way would be
<head>
<script>
document.addEventListener('onload',funciton(){
/* run code here */
});
</script>
</head>
since this allows for multiple eventhandlers to the same event
A better way is usually to react to domReady though.
Most javascript libraries support easy ways to hook into domReady. In jQuery for example you can do it like this:
$(function() {
/* code here will be run as soon as the dom is ready to be interacted with,
but before document.load occurs which means you don't have to wait for
images to load for example
*/
});
You should use the onload function because you will come across less problems when trying to debug it in different browsers.
The only other way I know to simulate this effect reliably is to have a script tag block just before the at the footer of the page.
Note that commands outside of functions in a script tag in the header run when the page loads. I don't know if this is actually equivalent to running functions explicitly onLoad via the body tag attribute, but it is tantamount to the same thing.
精彩评论