Add multiple window.onload events
P粉555696738
P粉555696738 2023-08-22 18:09:32
0
2
353

In my ASP.NET user control, I'm adding some JavaScript code to the window.onload event:

if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName)) Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, "window.onload = function() {myFunction();};", true);

My problem is that if there is already content in the onload event, this code overwrites it. How can I enable both user controls to execute JavaScript code in the onload event?

Editor: Thanks for the information about third-party libraries. I will remember.

P粉555696738
P粉555696738

reply all (2)
P粉354602955

Still an ugly solution (far inferior to using a framework oraddEventListener/attachEvent) is to save the currentonloadevent:

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粉253518620

    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); }
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!