我正在尝试动态地将jQuery包含到<head>
中。这是我的代码:
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
var script = document.createElement('script');
script.src = 'resources/js/jquery.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
alert(typeof jQuery);
}
效果很好,我在<script>
中看到<head>
标记; jquery.js文件也正确,错误少。即便如此,我alert(tyeof jQuery)
所获得的只是undefined
。为什么呢?
答案 0 :(得分:1)
尝试添加jQuery并在加载后分配回调。
在此处查看有和没有回调的示例:http://www.sitepoint.com/dynamically-load-jquery-library-javascript/
(function () {
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
//jQuery loaded
console.log('jquery loaded');
});
})();
答案 1 :(得分:0)
您需要添加
的侦听器 script.onload = myCallback;
事件并仅触发jQuery函数