The window.onload Problem

来源:百度文库 编辑:神马文学网 时间:2024/06/03 03:33:52
The window.onload Problem - Solved!
Well, when I say solved I mean solved for the two most important browsers - Internet Explorer and Mozilla/Firefox. Still that’s good enough isn’t it?
First, let me define the problem. The window.onload event is used by programmers to kick-start their web applications. This could be something trivial like animating a menu or something complex like initialising a mail application. The problem is that the onload event fires after all page content has loaded (including images and other binary content). If your page includes lots of images then you may see a noticeable lag before the page becomes active. What we want is a way to determine when the DOM has fully loaded without waiting for all those pesky images to load also.
Mozilla provides an (undocumented) event tailor-made for this: DOMContentLoaded. The following code will do exactly what we want on Mozilla platforms:
// for Mozilla browsersif (document.addEventListener) { document.addEventListener("DOMContentLoaded", init, null);}
So what about Internet Explorer?
IE supports a very handy (but non-standard) attribute for the
The contents of this external script would be a single line of code to call our onload event handler:
init();
There is a small problem with this approach. Other browsers will ignore the defer attribute and load the script immediately. There are several ways round this. My preferred method is to useconditional comments to hide the deferred script from other browsers:

IE also supportsconditional compilation. The following code is the JavaScript equivalent of the above HTML:
// for Internet Explorer/*@cc_on @*//*@if (@_win32) document.write("