如何在外部.js文件中包含jQuery?

时间:2012-05-29 20:05:16

标签: javascript jquery

我想为我的客户提供一个简单的代码来插入和获取我的插件。

代码:

<div id='banner-lujanventas'></div>
<script src="http://lujanventas.com/plugins/banners/script.js" type="text/javascript"></script>

问题是我的插件只适用于jQuery。如何检查我的script.js文件中是否安装了jQuery版本,如果不包含它? (我只能修改我的/script.js文件)

4 个答案:

答案 0 :(得分:5)

制作自己的脚本元素:

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。

答案 1 :(得分:2)

您可以检查jQuery变量

if (typeof jQuery === 'undefined') {
    // download it
}

用于下载选项,例如异步与document.write,请查看this article

答案 2 :(得分:1)

这样的事情:

<script>!window.jQuery && document.write(unescape('%3Cscript src="http://yourdomain.com/js/jquery-1.6.2.min.js"%3E%3C/script%3E'))</script>

答案 3 :(得分:0)

我挖出了一些寻找特定版本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...

    });
});
相关问题