Javascript를 사용하여 jquery 로드 여부 확인
Jquery Library가 HTML 페이지에 로드되어 있는지 확인하려고 합니다.잘 되는지 확인 중인데 뭔가 이상해요.제가 가지고 있는 것은 다음과 같습니다.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="/query-1.6.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if (jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
});
</script>
뭔가 이상하다.
jQuery를 사용하여 jQuery가 존재하는지 확인합니다.jQuery가 로드되지 않은 경우$()
다른 라이브러리를 사용하고 있고 해당 라이브러리가 동일한 라이브러리를 공유하지 않는 한 전혀 실행되지 않고 콜백도 실행되지 않습니다.$()
구문을 사용합니다.
삭제하다$(document).ready()
(와 같은 것을 사용)window.onload
대신) :
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
다음 링크:
if (typeof jQuery == 'undefined') {
// jQuery IS NOT loaded, do stuff here.
}
링크 댓글도 몇 개 더 있어요
if (typeof jQuery == 'function') {...}
//or
if (typeof $== 'function') {...}
// or
if (jQuery) {
alert("jquery is loaded");
} else {
alert("Not loaded");
}
이것으로 이 일을 끝낼 수 있는 좋은 방법이 거의 다 해결되었으면 좋겠어!!
if ('undefined' == typeof window.jQuery) {
// jQuery not present
} else {
// jQuery present
}
웹 페이지를 볼 때 콘솔 탭에서 이 작업을 빠르게 수행할 수 있습니다.
예:
$ === jQuery
만약 그것이 돌아온다면true
장전됐다는 뜻이지
실제로 문제를 해결할 수 있는 작은 수정 사항만 있으면 됩니다.
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
location.reload();
}
}
대신$(document).Ready(function()
사용하다window.onload = function()
.
메모: jQuery를 사용하여 jQuery를 테스트하지 마십시오(분명하지 않습니까).
jQuery 사용방법 »
if ('undefined' == typeof window.jQuery) {
$('#selector').appendTo('jQuery is NOT working');
} else {
$('#selector').appendTo('jQuery is working');
}
JavaScript ✔ 사용
if ('undefined' == typeof window.jQuery) {
document.getElementById('selector').innerHTML = "jQuery is NOT working";
} else {
document.getElementById('selector').innerHTML = "jQuery is working";
}
업데이트:
요즘 저는 이걸 생산에 쓰고 있는데 참 잘 작동해요.
jQuery를 실제로 로드하고 있는지 확인하십시오.로드하지 않으면 무한 루프가 발생할 수 있습니다.필요한 경우 카운터를 추가하고 끊을 것을 권장합니다.
(async() => {
console.log("waiting for jQuery");
while(!window.hasOwnProperty("jQuery")) {
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log("jQuery is loaded.");
})();
오래된 답변:존재 여부를 확인하고 존재하지 않는 경우 동적으로 로드할 수 있습니다.
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
async function load(){
if (!window.jQuery){
await loadScript(`https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js`);
}
console.log(jQuery);
}
load();
한다면jQuery
는 비동기적으로 로드되고 있습니다.정의될 때까지 대기하고 매시간 체크할 수 있습니다.
(function() {
var a = setInterval( function() {
if ( typeof window.jQuery === 'undefined' ) {
return;
}
clearInterval( a );
console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
}, 500 );
})();
이 메서드는 모든 변수에 사용할 수 있으며, 사용자가 나타나기를 기다리고 있습니다.
다음은 범용 크로스 브라우저 JQuery 로더입니다.문서의 DOM, HTML, CSS, 파일 및 리소스가 완전히 로드되었는지, JQuery 파일 자체가 구문 분석되어 실행 중인지 확인합니다.이 체커는 오래된 브라우저에서 작동하며 2001년으로 거슬러 올라가는 다양한 사용자 에이전트뿐만 아니라 오래된 Internet Explorer(4-11)도 지원합니다.이러한 브라우저에서 버그가 발생하지 않는 다양한 버전의 JQuery 자체에 의해서만 제한됩니다.슬프게도, 많은 이들이 그렇지 않다.
JQuery 파일 및 사용된 리소스를 다운로드, 구문 분석 및 JIT 컴파일할 때까지 JQuery에 의존하는 스크립트를 실행할 수 없습니다.또한 다음 코드를 사용하여 다른 리소스가 다운로드되기 전에 브라우저에서 DOM이 조기에 처리되는지 여부를 테스트하고 JQuery가 아닌 초기 스크립트를 실행하여 DOM에서 작업할 수 있습니다.다음 첫 번째 기능은 이 기능을 보여줍니다.이는 DOM만 구축되고 많은 CSS, 이미지 및 JavaScript 파일이 아직 다운로드되지 않은 것을 전제로 합니다.이 기능은 JQuery 및 기타 라이브러리보다 먼저 다운로드하여 어떤 이유로든 DOM을 조작하기 위해 지연된 스크립트가 필요한 경우에 유용합니다.
// EARLY JAVASCRIPT DOM PROCESSING (non-JQuery)
// Function to run as soon as the HTML is parsed and DOM rendered.
function DOMStart(state) {
if (state == null) {
state = "Unknown";
}
alert('DOM State: ' + state);
};
// FULLY LOADED WINDOW/DOCUMENT JAVASCRIPT PROCESSING, plus JQUERY CHECK
// TEST IF JQUERY IS LOADED (without using JQuery)
// Function to run as soon as all resources associated with the document are ready and JQuery script files are loaded.
function JQueryStart(state) {
if (state == null) {
state = "Unknown";
}
alert('JQuery State: ' + state);
//if (typeof window.jQuery !== 'undefined') { // Alt. Version #2 check
if (window.jQuery) {
// jquery is loaded...
alert("JQuery is loaded.");
// JQuery is downloaded. Now use JQuery to test if
// the document object model is fully
// loaded again from the point of view of JQuery.
// In most cases it is based on logic below.
// It is possible to load this function only when the
// DOM is ready instead of the whole document and all
// its files are ready and run a timer to detect when
// "window.jQuery" above is true. That would allow you
// to know JQuery is downloaded prior to the DOM and
// utilize it earlier.
$(document).ready(function () {
// ======== Begin JQuery Scripts ========
});
} else {
// JQuery did not load...
console.log("JQuery failed to load!");
alert("JQuery failed to load!");
}
};
// OLD BROWSER PAGE LOADER: This document loading check
// supports older browsers, including IE4+ and many older
// browsers like Firefox (2006), early Chrome (2010), etc.
// Note: "interactive" is when the document has finished
// loading and the document has been parsed and DOM is complete,
// but sub-resources such as scripts, images, style sheets and
// frames are still loading. "complete" is when all resources
// are loaded and right before the "Window.load event fires.
// Note: "document.onreadystatechange" has support in very old
// browsers amd may have support from IE4+, It fires as each
// state of the docuent load process changes below. IE 4-9 only
// supported "readyState" of "complete".
// If the document is already loaded and those events fired, run the JQuery function above.
if (document.readyState) {
if (document.readyState === "complete" // IE 4-9 only knows "complete"
|| document.readyState === "loaded") {
JQueryStart("Document fully loaded (early)");
} else {
// New browsers should run scripts when the HTML is
// parsed and the DOM built. Older IE browsers will
// not support the "DOMContentLoaded" event and instead
// fire when complete below. This allows newer browsers
// to fire only when the HTML DOM is ready, which happens
// right after the readyState=interactive fires.
if (window.addEventListener) {
// Listen for the "DOMContentLoaded" event, which occurs
// after "interactive" but when the HTML DOM is complete.
// This means the DOM is ready but other resources style
// sheets, other scripts, images, etc. may not be.
window.addEventListener('load', function () {
JQueryStart("Window fully loaded (2)");
}, false);
window.addEventListener('DOMContentLoaded', function () {
DOMStart("DOM complete (early)");
}, false);
} else {
// Run the older page "onreadystatechange" for older
// browsers. Below, runs when page resources are not
// yet fully loaded, so set up event listeners based
// on needs of old/new web browsers script support.
// This fires each time the document readyState changes,
// except in IE 4-9 that only supports "complete". Below,
// the DOM is loaded and parsed, but adding "interactive"
// to the condition below means other resources like CSS,
// images, etc may not have completed yet.
// Note: Add "interactive" below if needing to run early
// scripts as soon as the DOM is complete, and do not require
// styles sheets, script files, images, other resources, etc.
// Note: "interactive" fires before "DOMContentLoaded", but in
// IE 9 - 11 fires too early before parsing.
var isDone = false;
document.onreadystatechange = function () {
if (document.readyState === "complete" // IE 4-9 only knows "complete"
|| document.readyState === "loaded") {
if (!isDone) {
isDone = true;
JQueryStart("Document fully loaded");
}
}
else if (document.readyState === "interactive") {
DOMStart("Document interactive (early)");
}
};
}
}
} else {
// This is a fallback event format that works well in many older browsers.
window.onload = function () {
JQueryStart("Window fully loaded (1)");
};
};
.window.jQuery
e,n)가...그러면 jquery가 로드되어 정상적으로 동작하는 것이 확인됩니다.
빠른 방법은 개발자 콘솔에서 jQuery 명령을 실행하는 것입니다.임의의 브라우저에서 F12 키를 눌러 임의의 요소에 접속해 보겠습니다.
$("#sideTab2").css("background-color", "yellow");
언급URL : https://stackoverflow.com/questions/7341865/checking-if-jquery-is-loaded-using-javascript
'programing' 카테고리의 다른 글
"key = value;" 쌍의 문자열을 사전으로 변환하는 방법은 무엇입니까? (0) | 2022.12.07 |
---|---|
외부 키에 기반한 SQL 제약 조건 검사 (0) | 2022.12.07 |
반복하는 동안 목록에서 항목을 제거하려면 어떻게 해야 합니까? (0) | 2022.12.07 |
데이터베이스에 Enum을 저장하는 방법 (0) | 2022.12.07 |
Java SE API만 사용하는 Java의 단순한 HTTP 서버 (0) | 2022.12.07 |