Body Onload 이벤트를 사용해야하지만 타사 JavaScript 라이브러리가 납치되었습니다.

StackOverflow https://stackoverflow.com/questions/1704010

문제

동적 타임 라인을 그리기 위해 Simile을 사용하고 있습니다. 또한 사내 라이브러리를 사용하여 댓글 블로그를 추가하고 있습니다. 사내 라이브러리는 Body Element의 Onload 이벤트를 사용하여 초기화합니다.

<body onload="initComments('myID')">

그러나 Simile은 자신의 목적을 위해 Onload를 납치 한 것 같습니다.

직유 코드를 변경하지 않으면 이니셜 라이저를 어떻게 실행할 수 있습니까?

문제를 해결하기 위해 다른 라이브러리 (예 : jQuery)를 추가하지 않기를 원합니다.

도움이 되었습니까?

해결책

jQuery를 사용하십시오 $(document).ready 이벤트, 임의의 핸들러를 추가 할 수 있습니다 ( onload).

다른 팁

우선, 일반적으로 HTML에 태그 속성으로 JavaScript를 포함시키지 않기를 원합니다.

둘째, Simile은 The를 덮어 쓰고있을 것입니다 onload (당신과 같은 방식으로 사용). 따라서 Simile을 포함한 후 Onload 이벤트를 추가하고 싶을 것입니다.

jQuery 사용 :

<script src="/js/blah/simile.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        initComments('myID');
    });
</script>

라이브러리를 사용하지 않습니다 (발견 여기):

<script src="/js/blah/simile.js" type="text/javascript"></script>
<script type="text/javascript">
  function addOnloadEvent(fnc){
    if ( window.addEventListener ) {
      window.addEventListener( "load", fnc, false );
    } else if ( window.attachEvent ) {
      window.attachEvent( "onload", fnc );
    }
    else {
      var oldOnload = window.onload || function() {};
      window.onload = function(e) {
        oldOnload(e);
        window[fnc](e);
      };
    }
  }

  addOnloadEvent(function() { initComments('myID'); });
</script>

jQuery를 추가하고 사용합니다

$(document).ready(function(){
  // Your code here...
});

jQuery로 이것을 쓸 수있는 몇 가지 다른 방법이 있지만 이것이 가장 설명적인 것임을 알게됩니다.

어떤 종류의 JavaScript 개발을하고 있다면, 당신은 필요 jQuery를보고 있습니다. 완전히 달콤합니다!

앞서 언급 한 jQuery 솔루션 외에도 (그러나 사용하는 것이 좋습니다. 좋습니다) 여기에 일반 바닐라 JS 솔루션이 있습니다 (질문에서 jQuery에 대해 언급하지 않았기 때문에).

// Add this to top of your script.
window.onload = function () {
    for (var i = 0; arguments.callee.functions.length > i; i++) {
        arguments.callee.functions[i]();
    }
};
window.onload.functions = [];

// Now for every onload function you want to add, do:
window.onload.functions.push(initComments('myID'));

납치대로, 코드 후 직유로드 및 덮어 쓰기를 의미합니다. onload? 이 경우, 당신이 뒤에 도달했는지 확인하십시오 (저스틴과 같이 말한다), 당신이 직접 덮어 쓰기 전에 onload 어딘가에도 여전히 (자신의 핸들러에서) 호출됩니다.

즉, jQuery를 사용하지 않는 경우입니다.

여기를 살펴보면 jQuery가 사용하는 솔루션이 보일 것입니다.

http://dean.edwards.name/weblog/2006/06/again/

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
/*window.onload = init; */

마지막 줄에 댓글이 표시됩니다. 그것이 멀리 떨어져있는 경우, 당신은 그들을 clobber (무의미한) 또는 코드가 실행되지 않을 것이지만, 이것은 주요 브라우저에서 작동합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top