Program Club

window.onload 이벤트에 추가 하시겠습니까?

proclub 2021. 1. 7. 08:16
반응형

window.onload 이벤트에 추가 하시겠습니까?


이미 메서드 호출이 할당되면 window.onload 이벤트에 다른 메서드 호출을 추가하는 방법이 궁금합니다.

스크립트 어딘가에이 할당이 있다고 가정합니다.

 window.onload = function(){ some_methods_1() };

그리고 나중에 스크립트에서이 할당이 있습니다.

 window.onload = function(){ some_methods_2() };

약자로, 단지 some_methods_2호출됩니다. window.onload취소하지 않고 이전 콜백 에 추가 할 수있는 방법이 some_methods_1있습니까? (또한 동일한 기능 블록에 some_methods_1()둘 다를 포함하지 않음 some_methods_2()).

이 질문은 실제로는 window.onload아니지만 일반적으로 자바 스크립트에 관한 질문이라고 생각합니다 . window.onload다른 개발자가 스크립트에서 작업하고 window.onload(이전 코드를 보지 않고) 사용하는 코드를 추가하는 경우 내 onload 이벤트를 비활성화 하는 방식으로 무언가를 할당하고 싶지 않습니다 .

나는 또한 같은 것을 궁금합니다

  $(document).ready()

jquery에서. 이전 또는 이후에 올 수있는 것을 파괴하지 않고 어떻게 추가 할 수 있습니까?


jQuery를 사용하는 경우 특별한 작업을 수행 할 필요가 없습니다. 를 통해 추가 된 핸들러는 $(document).ready()서로 덮어 쓰지 않고 차례로 실행됩니다.

$(document).ready(func1)
...
$(document).ready(func2)

jQuery를 사용하지 않는 경우 addEventListenerKaraxuna에서 설명한대로를 사용할 수 있습니다 attachEvent.

참고 onload로 동일하지 않습니다 $(document).ready()- CSS에 대한 전 대기, 이미지 ...뿐만 아니라, 동안 DOM 트리 후자의 대기는. 최신 브라우저 (및 IE9 이후 IE) DOMContentLoaded는 jQuery ready이벤트에 해당하는 문서 이벤트를 지원 하지만 IE <9는 지원하지 않습니다.

if(window.addEventListener){
  window.addEventListener('load', func1)
}else{
  window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
  window.addEventListener('load', func2)
}else{
  window.attachEvent('onload', func2)
}

두 옵션을 모두 사용할 수없는 경우 (예 : DOM 노드를 다루지 않는 경우) 계속이 작업을 수행 할 수 있습니다 ( onload예로 사용하고 있지만 다른 옵션 은에서 사용할 수 있음 onload).

var oldOnload1=window.onload;
window.onload=function(){
  oldOnload1 && oldOnload1();
  func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
  oldOnload2 && oldOnload2();
  func2();
}

또는 가져 오기 / 내보내기 IIFE 패턴을 사용하여 전역 네임 스페이스 오염 (및 네임 스페이스 충돌 발생 가능성)을 방지하려면 :

window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func1();
  }
})(window.onload)
...
window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func2();
  }
})(window.onload)

대신 attachEvent (ie8) 및 addEventListener를 사용할 수 있습니다.

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

기본적으로 두 가지 방법이 있습니다

  1. store the previous value of window.onload so your code can call a previous handler if present before or after your code executes

  2. using the addEventListener approach (that of course Microsoft doesn't like and requires you to use another different name).

The second method will give you a bit more safety if another script wants to use window.onload and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.

Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.


This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

ReferenceURL : https://stackoverflow.com/questions/15564029/adding-to-window-onload-event

반응형