P粉3546029552023-08-23 14:45:25
Still an ugly solution (far inferior to using a framework or addEventListener
/attachEvent
) is to save the current onload
event:
function addOnLoad(fn) { var old = window.onload; window.onload = function() { old(); fn(); }; } addOnLoad(function() { // 在这里编写你的代码 }); addOnLoad(function() { // 在这里编写你的代码 }); addOnLoad(function() { // 在这里编写你的代码 });
Please note that frameworks like jQuery will provide a way to execute code when the DOM is ready, not when the page loads.
DOM ready means that your HTML has been loaded, but external components (such as images or style sheets) have not yet been loaded, which allows you to be called before the load event fires.
P粉2535186202023-08-23 10:50:31
Most of the proposed "solutions" are specific to Microsoft, or require huge libraries. This is a good approach. It works with W3C-compliant browsers and Microsoft IE.
if (window.addEventListener) // W3C标准 { window.addEventListener('load', myFunction, false); // 注意 **不是** 'onload' } else if (window.attachEvent) // Microsoft { window.attachEvent('onload', myFunction); }