Javascript로 jQuery로드 및 jQuery 사용
다음을 사용하여 jQuery 라이브러리를 dom에 추가하고 있습니다.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
그러나 내가 실행할 때 :
jQuery(document).ready(function(){...
콘솔이 오류를보고합니다.
Uncaught ReferenceError: jQuery is not defined
jQuery를 동적으로로드하고 DOM에 있으면 어떻게 사용합니까?
여기에 작은 예제와 함께 작동하는 JSFiddle이 있으며, 원하는 것을 정확히 보여줍니다 (요청을 오해하지 않는 한) : http://jsfiddle.net/9N7Z2/188/
자바 스크립트를 동적으로로드하는 방법에는 몇 가지 문제가 있습니다. jQuery와 같은 기본 프레임 워크의 경우 실제로 정적으로로드하고 싶을 것입니다. 그렇지 않으면 전체 JavaScript로드 프레임 워크를 작성해야하기 때문입니다.
기존 JavaScript 로더 중 일부를 사용하거나 window.jQuery정의를 확인 하여 직접 작성할 수 있습니다 .
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
IE8과 같은 정말 오래된 브라우저 를 지원해야하는 경우 load이벤트 처리기가 실행되지 않는다는 점을 기억하십시오 . 이 경우 repeat window.jQuery사용 이 존재하는지 폴링해야합니다 window.setTimeout. 여기에 해당 방법으로 작동하는 JSFiddle이 있습니다. http://jsfiddle.net/9N7Z2/3/
당신이해야 할 일을 이미 한 많은 사람들이 있습니다. 다음과 같은 기존 JavaScript Loader 프레임 워크 중 일부를 확인하십시오.
https://developers.google.com/loader/(더 이상 문서화되지 않음)http://yepnopejs.com/(지원 중단됨)- http://requirejs.org/
jQuery를 동적으로로드하는 다른 방법이 있습니다 ( source ). 당신은 또한 사용할 수 있습니다
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');
을 사용하는 것은 나쁜 습관으로 간주 document.write되지만 완성을 위해 언급하는 것이 좋습니다.
document.write가 "나쁜 관행"으로 간주되는 이유를 참조하십시오 . 이유 때문에. 프로 즉 document.write있도록 콜백 함수를 만들 필요가 없습니다, 다른 assests로드에서 페이지를 차단한다.
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
google.load("jquery", "1.7.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
</script>
그러나 그는 최적의 성능과 관련하여 다음을 수행하는 것과 비교할 수 없다는 것을 인정합니다.
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
<script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>
jQuery가로드를 마친 후에 코드를 실행해야합니다.
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
// your jQuery code here
}
또는 비동기 함수에서 실행하는 await경우 위 코드에서 사용할 수 있습니다 .
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here
페이지에 jQuery가 이미 있는지 먼저 확인하려면 다음을 시도 하십시오.
이 오류가 발생하는 이유는 JavaScript가 스크립트가로드 될 때까지 기다리지 않기 때문입니다.
jQuery(document).ready(function(){...
스크립트가 준비되었다는 보장은 없습니다 (그리고 절대 없을 것입니다).
This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.
var jQueryIsReady = function(){
//Your JQuery code here
}
var checkJquery = function(){
if(typeof jQuery === "undefined"){
return false;
}else{
clearTimeout(interval);
jQueryIsReady();
}
}
var interval = setInterval(checkJquery,1000);
Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:
I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:
<title>jQuery+RequireJS Sample Page</title>
<script src="scripts/require.js"></script>
<script>
require({
baseUrl: 'scripts',
paths: {
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
},
priority: ['jquery']
}, ['main']);
</script>
HTML:
<html>
<head>
</head>
<body>
<div id='status'>jQuery is not loaded yet.</div>
<input type='button' value='Click here to load it.' onclick='load()' />
</body>
</html>
Script:
<script>
load = function() {
load.getScript("jquery-1.7.2.js");
load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
}
// dynamically load any javascript file.
load.getScript = function(filename) {
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.setAttribute("src", filename)
if (typeof script!="undefined")
document.getElementsByTagName("head")[0].appendChild(script)
}
</script>
참고URL : https://stackoverflow.com/questions/10113366/load-jquery-with-javascript-and-use-jquery
'IT TIP' 카테고리의 다른 글
| JavaScript에서 익명 함수에 인수를 어떻게 전달할 수 있습니까? (0) | 2020.10.26 |
|---|---|
| RichTextBox를 맨 아래로 스크롤하려면 어떻게합니까? (0) | 2020.10.26 |
| 데이터베이스의 카디널리티는 무엇입니까? (0) | 2020.10.26 |
| UITextView의 NSAttributedString에 글꼴을 설정하면 줄 간격이 무시됩니다. (0) | 2020.10.26 |
| 테두리의 두께를 백분율로 설정하는 방법은 무엇입니까? (0) | 2020.10.26 |