프로그래밍 언어/HTML,CSS,JS
$ (document) .jQuery 를 대체 하는 방법
Rateye
2021. 9. 8. 10:29
728x90
반응형
질문 : $ (document) .jQuery 없이도 동등 함
$(document).ready
사용하는 스크립트가 있지만 jQuery에서 다른 것을 사용하지 않습니다. jQuery 종속성을 제거하여 가볍게하고 싶습니다.
jQuery를 사용하지 않고 내 자신의 $(document).ready
내가 사용하는 것을 알고 window.onload
등, 동일하지 않습니다 window.onload
모든 이미지, 프레임, 등 후 화재가로드되었다.
답변
IE8은 아니지만 99 % 이상의 브라우저 에서 지원하는 표준 기반 대체 DOMContentLoaded
가 있습니다.
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery의 기본 기능은 아래에 설명 된 것처럼 window.onload보다 훨씬 더 복잡합니다.
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
출처 : https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery
728x90
반응형