Home  >  Q&A  >  body text

Add multiple window.onload events

<p>In my ASP.NET user control, I'm adding some JavaScript code to the <code>window.onload</code> event: </p> <pre class="brush:php;toolbar:false;">if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName)) Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, "window.onload = function() {myFunction();};", true);</pre> <p>My problem is that if there is already content in the <code>onload</code> event, this code overwrites it. How can I enable both user controls to execute JavaScript code in the <code>onload</code> event? </p> <p><strong>Editor: </strong>Thanks for the information about third-party libraries. I will remember. </p>
P粉555696738P粉555696738447 days ago430

reply all(2)I'll reply

  • P粉354602955

    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.

    reply
    0
  • P粉253518620

    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);
    }

    reply
    0
  • Cancelreply