我正在尝试动态包含 jquery 并且我使用了以下代码-
index.php
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
包含jquery.js
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict();
}
但是 jquery 功能不起作用,它没有打印段落标记:-( 请帮助我。提前致谢
最佳答案
这不起作用,因为您的 $(document).ready(...
行在 before jQuery 加载之前运行,因此它会失败,因为 $
code> 未定义(抛出 ReferenceError
),或者它引用了 jQuery 之外的其他内容。此外,您在加载 jQuery 之前调用 jQuery.noConflict()
,并且如果调用did工作,这意味着$
根本不再引用jQuery,所以$(document).ready(...
还是不行。
在任何现代浏览器中,您都可以在要添加的 script
元素上使用 load
事件,该事件会告诉您脚本已加载。可能最好将回调传递到您对 includejquery.js
进行的调用中,如下所示:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
includejQuery(function($){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js
:
function includejQuery(callback) {
if(window.jQuery)
{
// jQuery is already loaded, set up an asynchronous call
// to the callback if any
if (callback)
{
setTimeout(function() {
callback(jQuery);
}, 0);
}
}
else
{
// jQuery not loaded, load it and when it loads call
// noConflict and the callback (if any).
var script = document.createElement('script');
script.onload = function() {
jQuery.noConflict();
if (callback) {
callback(jQuery);
}
};
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
那里的变化:
在
includejquery.js
中,只需定义一个函数并等待被调用即可。让该函数接受回调。
让它等待脚本加载。
加载脚本后,调用
jQuery.noConflict
,然后,如果有回调,则调用它并传入jQuery
函数。在 HTML 中,我调用该函数,并接收它以
$
形式传递给我的参数,因此仅在该函数内,$ === jQuery
即使在它之外,它也不会(因为noConflict
)。
关于javascript - 如何使用纯 javascript 在任何网站中动态包含 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25442462/