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.
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.