我正在研究JavaScript小部件。下面是我的代码调用小部件html页面。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="http://localhost/widget1/widget1.js" type="text/javascript"></script>
<script src="http://localhost/widget1/widget2.js" type="text/javascript"></script>
</head>
<body>
<div style="width: 100%; height: 100%;display: inline-block;background-color:#eee">
<h1 align="center"><a href="#">Demo test</a></h1>
<div id="container1" style="width: 45%; height: 300px;display: inline-block;margin:30px"></div>
<div id="container2" style="width: 45%; height: 300px;display: inline-block;margin:30px"></div>
<br>
</div>
</body>
</html>
以下是我的widgets1.js和widgets2.js文件:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (typeof jQuery == undefined || typeof jQuery != '1.9.1') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("id", "jqueryLib");
script_tag.setAttribute("src", "http://code.jquery.com/jquery-1.9.1.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
//}
} else {
//The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
})();
在html页面上我首先加载widgets1.js文件,其次我正在加载widgets2.js文件。我正在检查http://code.jquery.com/jquery-1.9.1.js文件,如果没有定义加载。
此文件加载到widgets1.js文件中,但http://code.jquery.com/jquery-1.9.1.js文件再次加载到widgets2.js文件中,我不会再次加载。
我正在检查typeof jQuery == undefined但不验证和文件加载两次。
这不是检查它的好方法,但if语句不起作用。尝试if (!window.jQuery)
,这应该工作。
另外,这部分:
jQuery = window.jQuery;
main();
你可能想把它放在else语句之外,因为我假设你总是想要执行这两行。
几点说明:
typeof
时,你应该将它与一个字符串进行比较。所以typeof jQuery !== 'undefined'
(注意引号)是正确的检查。typeof jQuery === '1.9.1'
将永远不会成真。如果加载typeof jQuery
将是'function'
。试试这个,
var s;
if (void 0 === window.jQuery || "1.4.2" !== window.jQuery.fn.jquery) {
var i = document.createElement("script");
i.setAttribute("type", "text/javascript"), i.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"), i.readyState ? i.onreadystatechange = function() {
("complete" == this.readyState || "loaded" == this.readyState) && e()
} : i.onload = e, (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(i)
} else s = window.jQuery, l()
}