Nice programing

여러 window.onload 이벤트 추가

nicepro 2020. 12. 7. 20:41
반응형

여러 window.onload 이벤트 추가


내 ASP.NET 사용자 컨트롤에서 window.onload이벤트에 몇 가지 JavaScript를 추가하고 있습니다 .

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

내 문제는 onload이벤트에 이미 무언가가 있으면 덮어 쓰는 것보다 큽니다. onload이벤트 에서 각각 JavaScript를 실행할 수 있도록 두 개의 사용자 컨트롤을 허용하려면 어떻게해야합니까?

편집 : 타사 라이브러리에 대한 정보에 감사드립니다. 명심하겠습니다.


제안 된 대부분의 "솔루션"은 Microsoft 전용이거나 확장 된 라이브러리가 필요합니다. 한 가지 좋은 방법이 있습니다. 이것은 W3C 호환 브라우저 및 Microsoft IE에서 작동합니다.

if (window.addEventListener) // W3C standard
{
  window.addEventListener('load', myFunction, false); // NB **not** 'onload'
} 
else if (window.attachEvent) // Microsoft
{
  window.attachEvent('onload', myFunction);
}

현재 이벤트 를 저장 하는 추악한 솔루션 (프레임 워크 또는 addEventListener/ 을 사용하는 것보다 훨씬 열등함)이 여전히 있습니다 .attachEventonload

function addOnLoad(fn)
{ 
   var old = window.onload;
   window.onload = function()
   {
       old();
       fn();
   };
}

addOnLoad(function()
{
   // your code here
});
addOnLoad(function()
{
   // your code here
});
addOnLoad(function()
{
   // your code here
});

jQuery와 같은 프레임 워크는 페이지가로드 될 때가 아니라 DOM이 준비 될 때 코드를 실행하는 방법을 제공합니다.

DOM이 준비되었다는 것은 HTML이로드되었지만 이미지 나 스타일 시트와 같은 외부 구성 요소는로드되지 않았 음을 의미하므로로드 이벤트가 발생하기 오래 전에 호출 할 수 있습니다.


오늘 비슷한 문제가 있었으므로 index.js다음과 같이 해결했습니다 .

window.onloadFuncs = [];

window.onload = function()
{
 for(var i in this.onloadFuncs)
 {
  this.onloadFuncs[i]();
 }
}

onload 이벤트를 첨부하려는 추가 js 파일에서 다음을 수행하면됩니다.

window.onloadFuncs.push(function(){
 // code here
});

나는 일반적으로 jQuery를 사용하지만 이번에는 잠시 동안 내 마음을 사용해야하는 순수한 js로 제한되었습니다!


Mootools 는 사용하기 매우 쉬운 또 다른 훌륭한 JavaScript 프레임 워크이며 RedWolves가 jQuery 를 사용하여 말했듯 이 원하는만큼 핸들러를 계속 실행할 수 있습니다.

모든 * .js 파일에 대해 함수에 코드를 래핑합니다.

window.addEvent('domready', function(){
    alert('Just put all your code here');
});

And there are also advantages of using domready instead of onload


Try this:

window.attachEvent("onload", myOtherFunctionToCall);

function myOtherFunctionToCall() {
    // do something
}

edit: hey, I was just getting ready to log in with Firefox and reformat this myself! Still doesn't seem to format code for me with IE7.


I don't know a lot about ASP.NET, but why not write a custom function for the onload event that in turn calls both functions for you? If you've got two functions, call them both from a third script which you register for the event.


Have you considered using something like JQuery which provides a framework for cleaning adding multiple event handlers?


Actually, according to this MSDN page, it looks like you can call this function multiple times to register multiple scripts. You just need to use different keys (the second argument).

Page.ClientScript.RegisterStartupScript(
    this.GetType(), key1, function1, true);

Page.ClientScript.RegisterStartupScript(
    this.GetType(), key2, function2, true);

I believe that should work.


You can do this with jquery

$(window).load(function () {
    // jQuery functions to initialize after the page has loaded.
});

참고URL : https://stackoverflow.com/questions/9434/add-multiple-window-onload-events

반응형