jQuery의 $.ready()에 상당하는 Vanilla JavaScript - 페이지/DOM이 준비되었을 때 함수를 호출하는 방법
사용하면 jQuery를 알 수 ..ready()
★★★★
$('document').ready(function(){});
단, 라이브러리 백업 없이 표준 JavaScript로 작성된 함수를 실행하고 페이지가 처리 준비가 되면 바로 함수를 실행한다고 가정해 보겠습니다.어떻게 접근하면 좋을까요?
제가 할 수 있는 일:
window.onload="myFunction()";
또,를 사용할 도 있고,body
삭제:
<body onload="myFunction()">
, 은...body
★★★★★★★★★★★★★★★★★」html
★★★★
<script type="text/javascript">
myFunction();
</script>
jQuery와 같은 이상의 함수를 발행하는 크로스 준거 입니까?$.ready()
크로스 브라우저의 모든 호환성을 실현하는 프레임워크가 없는 경우 가장 간단한 방법은 본문 끝에 있는 코드를 호출하는 것입니다.가 더 빠릅니다.onload
모든 이미지가 로드되는 것이 아니라 DOM이 준비될 때까지 대기하기 때문입니다.모든 브라우저에서 사용할 수 있습니다.
<!doctype html>
<html>
<head>
</head>
<body>
Your HTML here
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
})();
</script>
</body>
</html>
브라우저및 Chrome,Safari 중 하나)의 경우 "" (IE9" "Chrome, Firefox" "Safari")와 같은 할 수 .$(document).ready()
어디서든 콜할 수 있는 방식(콜 스크립트의 위치를 신경 쓰지 않고)은 다음과 같은 것을 사용할 수 있습니다.
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" || document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
사용방법:
docReady(function() {
// DOM is loaded and ready for manipulation here
});
브라우저 버전이 필요하고, 「」( 「IE」)을 .window.onload
jQuery와 같은 JQuery를 합니다.$(document).ready()
it.의 기능에 상당히 관련이 이것은 브라우저의 기능에 따라 상당히 관련이 있습니다.
jQuery의 기능에 대해 간단히 설명하겠습니다(스크립트 태그를 붙이면 어디서든 작동합니다).
서포트되고 있는 경우는, 다음의 표준을 시험합니다.
document.addEventListener('DOMContentLoaded', fn, false);
다음 항목에 대한 폴백:
window.addEventListener('load', fn, false )
또는 이전 버전의 IE에서는 다음을 사용합니다.
document.attachEvent("onreadystatechange", fn);
다음 항목에 대한 폴백:
window.attachEvent("onload", fn);
그리고 IE 코드 경로에는 잘 모르는 회피책이 몇 가지 있는데 프레임과 관련이 있는 것 같습니다.
jQuery를 입니다..ready()
Javascript 작성 :
(function(funcName, baseObj) {
// The public function name defaults to window.docReady
// but you can pass in your own object and own function name and those will be used
// if you want to put them in a different namespace
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);
최신 버전의 코드는 GitHub에서 https://github.com/jfriend00/docReady에 공개되어 있습니다.
사용방법:
// pass a function reference
docReady(fn);
// use an anonymous function
docReady(function() {
// code here
});
// pass a function reference and a context
// the context will be passed to the function as the first argument
docReady(fn, context);
// use an anonymous function with a context
docReady(function(context) {
// code here that can use the context argument that was passed to docReady
}, ctx);
이는 다음에서 테스트되었습니다.
IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safari 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices
실장 및 테스트베드: http://jsfiddle.net/jfriend00/YfD3C/
동작의 개요를 다음에 나타냅니다.
- IIE(즉시 호출된 함수식)를 생성하여 비공개 상태 변수를 사용할 수 있도록 합니다.
- 함수를 선언합니다.
docReady(fn, context)
docReady(fn, context)
가 호출되어 준비 핸들러가 이미 기동하고 있는지 여부를 확인합니다.경우 새로 의 이 가 "JS"로 합니다.setTimeout(fn, 1)
.- 준비 핸들러가 아직 기동하지 않은 경우는, 이 새로운 콜백을, 나중에 콜 하는 콜백의 리스트에 추가합니다.
- 문서가 이미 준비되었는지 확인합니다.이 경우 모든 준비 핸들러를 실행합니다.
- 문서가 언제 준비되는지 알 수 있도록 이벤트 수신기를 아직 설치하지 않은 경우 지금 설치합니다.
- if
document.addEventListener
경우 합니다..addEventListener()
쌍방에"DOMContentLoaded"
★★★★★★★★★★★★★★★★★」"load"
필요하지 "부하"는 안전을 위한 백업 이벤트이므로 필요하지 않습니다. - if
document.addEventListener
하지 않습니다 합니다.이벤트 핸들러를 인스톨 합니다..attachEvent()
★★★★★★에"onreadystatechange"
★★★★★★★★★★★★★★★★★」"onload"
벤트입입니니다 - 서서
onreadystatechange
이벤트, 이벤트, 이벤트, 합니다.document.readyState === "complete"
그리고 만약 그렇다면, 모든 준비된 핸들러를 해고하는 함수를 호출한다. - 다른 모든 이벤트핸들러에서는 함수를 호출하여 모든 준비된 핸들러를 기동합니다.
- 모든 준비 완료 핸들러를 호출하는 함수에서 상태 변수를 확인하여 이미 실행되었는지 확인합니다.그랬다면 아무것도 하지 마세요.아직 호출되지 않은 경우, 준비된 함수의 배열을 반복하여 추가된 순서대로 호출합니다.이러한 모든 것이 호출되었음을 나타내는 플래그를 설정하여 두 번 이상 실행되지 않도록 합니다.
- 기능 배열을 클리어하여 사용 중인 모든 닫힘을 해제합니다.
된 핸들러docReady()
등록된 순서대로 실행이 보증됩니다.
「 」에 docReady(fn)
준비되면 되는 대로 콜백이 이 설정됩니다.setTimeout(fn, 1)
이것에 의해, 발신 코드는, JS 의 현재 스레드가 종료하고 나서 곧바로 발신 순서를 보관 유지하는 경우에서도, 항상 나중에 호출되는 비동기 콜백이라고 간주할 수 있습니다.
jQuery를 사용하지 않고 VANILA 플레인 JavaScript를 실행하는 경우 (Internet Explorer 9 이후)를 사용해야 합니다.
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});
jQuery에 합니다..ready
:
$(document).ready(function() {
console.log("Ready!");
});
또한, jQuery는 ready가 발생한 후에 실행됩니다.
$(function() {
console.log("ready!");
});
아래와 혼동하지 마십시오(DOM 준비는 되어 있지 않습니다).
다음과 같은 자가 실행 IIE는 사용하지 마십시오.
Example:
(function() {
// Your page initialization code here - WRONG
// The DOM will be available here - WRONG
})();
이 IIFE는 DOM이 로딩될 때까지 기다리지 않습니다. (최신 버전의 Chrome 브라우저에 대해서도 말하고 있습니다!)
여기에서는 모든 브라우저에서 작동하는 순수 자바스크립트 트릭과 함께 몇 가지 가능한 방법을 언급하고 싶습니다.
// with jQuery
$(document).ready(function(){ /* ... */ });
// shorter jQuery version
$(function(){ /* ... */ });
// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);
// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
alert('DOM Ready!');
});
여기서의 요령은 원저자가 설명한 바와 같이 document.readyState 속성을 확인하는 것입니다.문자열이 포함되어 있는 경우in
: (예:)uninitialized
★★★★★★★★★★★★★★★★★」loading
5개 중 첫 번째 2개의 DOM 준비 상태)는 타임아웃을 설정하고 다시 확인합니다.그렇지 않으면 전달된 함수를 실행합니다.
그리고 여기 jsFiddle이 모든 브라우저에서 작동하는 트릭을 보여줍니다.
Tutorialzine이 이 내용을 그들의 책에 포함시켜줘서 고마워.
IE9 및 최신 Firefox 및 Chrome에서 테스트되었으며 IE8에서도 지원됩니다.
document.onreadystatechange = function () {
var state = document.readyState;
if (state == 'interactive') {
init();
} else if (state == 'complete') {
initOnCompleteLoad();
}
};
예: http://jsfiddle.net/electricvisions/Jacck/
업데이트 - 재사용 가능한 버전
저는 방금 다음과 같은 것을 개발했습니다.이는 하위 호환성이 없는 jQuery 또는 Dom ready와 같은 다소 단순한 기능입니다.아마 좀 더 다듬어야 할 것 같아요.Chrome, Firefox 및 IE의 최신 버전(10/11)에서 테스트되었으며 설명대로 이전 브라우저에서 작동합니다.문제가 발견되면 업데이트하겠습니다.
window.readyHandlers = [];
window.ready = function ready(handler) {
window.readyHandlers.push(handler);
handleState();
};
window.handleState = function handleState () {
if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
while(window.readyHandlers.length > 0) {
(window.readyHandlers.shift())();
}
}
};
document.onreadystatechange = window.handleState;
사용방법:
ready(function () {
// your code here
});
이 스크립트는 JS의 비동기 로드를 처리하도록 작성되어 있지만 최소화할 경우를 제외하고 먼저 이 스크립트를 동기화할 수 있습니다.나는 그것이 개발에 유용하다는 것을 알았다.
최신 브라우저에서는 스크립트의 비동기 로딩도 지원되므로 조작성이 더욱 향상됩니다.비동기 지원으로 페이지를 렌더링하면서 여러 스크립트를 동시에 다운로드할 수 있습니다.비동기적으로 로드된 다른 스크립트에 의존할 때는 주의하거나 browserify 같은 것을 사용하여 종속성을 처리합니다.
수 있는 . HubSpot을 포함한 jQuery는 jQuery를 사용합니다.ready
http://youmightnotneedjquery.com/ #준비완료
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
인라인 사용 예:
ready(function() { alert('hello'); });
무슨 질문인지 잘 모르겠습니다만, 이것이 도움이 될 수도 있습니다.
window.onload = function(){
// Code. . .
}
또는 다음 중 하나를 선택합니다.
window.onload = main;
function main(){
// Code. . .
}
메서드(마감 본문 태그 앞에 스크립트 배치)
<script>
myFunction()
</script>
</body>
</html>
는 오래된 브라우저와 새로운 브라우저를 지원하는 신뢰성 높은 방법입니다.
준비가 되어 있습니다!
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
사용법
ready(function(){
//some code
});
자기 호출 코드인 경우
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
지원: IE9+
다음은 Ram-swaroop의 "모든 브라우저에서 작동" 버라이어티로 모든 브라우저에서 작동되는 깔끔한 버전입니다.
function onReady(yourMethod) {
var readyStateCheckInterval = setInterval(function() {
if (document && document.readyState === 'complete') { // Or 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
// use like
onReady(function() { alert('hello'); } );
단, 10밀리초의 추가 실행이 필요하기 때문에 실행하지 않는 보다 복잡한 방법이 있습니다.
function onReady(yourMethod) {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
setTimeout(yourMethod, 1); // Schedule to run immediately
}
else {
readyStateCheckInterval = setInterval(function() {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
}
// Use like
onReady(function() { alert('hello'); } );
// Or
onReady(functionName);
프레임워크 없이 DOM이 준비되었는지 확인하는 방법도 참조하십시오.
document.ondomcontentready=function(){}
하지만 브라우저와 완전히 호환되지는 않습니다.
jQuery min을 사용하는 것이 좋을 것 같습니다.
언급URL : https://stackoverflow.com/questions/9899372/vanilla-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-whe
'programing' 카테고리의 다른 글
Python try...제외(쉼표 vs 'as' 제외) (0) | 2022.09.08 |
---|---|
현재 사용하고 있는 CodeIgniter 버전은 무엇입니까? (0) | 2022.09.08 |
두 개의 dicts(양쪽에 나타나는 키의 값을 추가하는)를 조합하는 피토닉 방법이 있습니까? (0) | 2022.09.05 |
특정 행에만 MySQL 권한을 부여하는 방법 (0) | 2022.09.05 |
Java를 사용하여 문자열에서 중복된 공백을 제거하려면 어떻게 해야 합니까? (0) | 2022.09.05 |