SoFunction
Updated on 2025-04-06

js dynamically add onload, onresize, and onscroll events (alternative method)

The onload, onresize, and onscroll events of window are different from other events. They cannot be added with attachEvent or addEventListener.

In other words, it can only be done like this (taking onload as an example, the same below):
Copy the codeThe code is as follows:

= function()
{
// ...
};

But there is a problem with this. When you want to add a new event handler to onload, you cannot directly assign a value, otherwise the previous assignment will be overwritten.

Can do this
Copy the codeThe code is as follows:

var oldLoadHandler = ;
= function()
{
if (oldLoadHandler)
{
oldLoadHandler();
}
newLoadHandler();
};

In ezj, it is even more convenient.
Copy the codeThe code is as follows:

$(window).ready(onloadHandler1);
$(window).ready(onloadHandler2);


illustrate
The onload event we usually come into contact with is , but this is actually due to misleading by IE. The correct one should be , which is valid in IE, Firefox, and Chrome.