Add multiple window.onload events
P粉555696738
2023-08-22 18:09:32
<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>
Still an ugly solution (far inferior to using a framework or
addEventListener
/attachEvent
) is to save the currentonload
event: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.
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.