如何在外部.js文件中包含 jQuery
How to include jQuery in an external .js file?
我想为我的客户提供一个简单的代码来插入和获取我的插件。
代码:
<div id='banner-lujanventas'></div>
<script src="http://lujanventas.com/plugins/banners/script.js" type="text/javascript"></script>
问题是我的插件仅适用于jQuery。如何检查我的脚本.js文件中是否安装了 jQuery 版本,如果没有包含它?(我只能修改我的/script.js 文件)
创建自己的脚本元素:
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
//edit
window.onload = function() {
$(function(){ alert("jQuery + DOM loaded."); });
}
你必须把你真正的onload代码放在一个window.onload()
函数中,而不是放在一个$(document).ready()
函数中,因为jquery.js此时不需要加载。
你可以检查 jQuery 变量
if (typeof jQuery === 'undefined') {
// download it
}
对于下载选项,例如异步与 document.write
,看看这篇文章。
像这样:
<script>!window.jQuery && document.write(unescape('%3Cscript src="http://yourdomain.com/js/jquery-1.6.2.min.js"%3E%3C/script%3E'))</script>
我挖出了一些旧代码,这些代码查找特定版本的 jQuery 并在找不到时加载它,并且它避免与页面已经使用的任何现有 jQuery 冲突:
// This handles loading the correct version of jQuery without
// interfering with any other version loaded from the parent page.
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-2.1.0.min.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
}
})(window, document, "2.1", function($) {
$(document).ready(function() {
console.log("Using jQuery version: " + $.fn.jquery);
// Your code goes here...
});
});
相关文章:
- 在JavaScript中包含jQuery
- Python 在包含 JQuery 时抛出 KeyError
- 如何在javascript模块中包含jquery而不与全局名称空间冲突
- 如何在One'中包含jQuery.js;s Own.js在$(document).ready之前
- 包含jquery的Javascript在Internet Explorer中不起作用
- Chrome扩展-当我包含jQuery库时,JS为什么会抱怨
- 在我的页面上包含jquery库有什么缺点吗
- 在js文件中包含jquery
- 包含jquery对象的javascript对象
- 在 WordPress-plugin 中包含 jQuery
- 包含 jQuery 会导致标准 JavaScript 停止运行
- 包含 jquery.无冲突
- 我们可以在 Java 脚本验证函数中包含 jQuery 吗?
- 如何替换包含 jquery 捕获的 html 的变量中出现的字符串
- 如何在我的 Rails 应用程序的一个页面上仅包含 JQuery 库
- 如何在外部.js文件中包含 jQuery
- 如何包含 jquery.validate.js 文件(在本地目录中)并在表单验证中使用它
- 如何使 IDE 识别出我在 HTML 文件中包含 jquery
- 在页面中包含jquery.js和javascript.js
- 当通过导入包含 jQuery 时,窗口加载事件不会触发