如何知道JQuery是否已完成加载

如何知道JQuery是否已完成加载

本文介绍了如何知道JQuery是否已完成加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些情况说我需要使用这样的一个javascript加载jQuery:

For some case say I need to load jQuery using a piece of javascript like this :

 <script type="text/javascript">
    if (typeof jQuery == 'undefined')
    {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
    }
 </script>

但是我怎么知道JQuery已经完成加载以便我可以使用它。

But how will I know that JQuery has finished loading so that I can use it.

推荐答案

您必须编写代码来检测何时加载动态加载的脚本,不幸的是,它在某些旧版浏览器中的工作方式略有不同所以它不是尽可能简单。以下是有关如何执行此操作的参考文章:

You will have to write code to detect when a dynamically loaded script is loaded and unfortunately, it works slightly different in some older browsers so it isn't as simple as it could be. Here's a good reference article on how to do that: http://www.ejeliot.com/blog/109

以下是该文章的部分代码:

Here's some of the code from that article:

function loadScript(sScriptSrc, oCallback) {

    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');

    // make sure callback isn't run more than once
    function runCallback() {
        if (oCallback) {
            oCallback();
            oScript.onload = oScript.onreadystatechange = null;
            oCallback = null;
        }
    }

    oScript.type = 'text/javascript';
    // most browsers
    oScript.onload = runCallback;
    // IE 6 & 7
    oScript.onreadystatechange = function() {
        if (this.readyState === 'complete') {
            runCallback();
        }
    }
    oScript.src = sScriptSrc;
    oHead.appendChild(oScript);
}

或者,您可以使用其中一个为您工作的小库。您可以在此处查看其中一些列表:。虽然我不确定您是否想要使用另一个库来协助加载您的主库。

Alternatively, you could use one of the tiny libraries that does this work for you. You can see a list of some of those here: http://microjs.com/#loader. Though I'm not sure you want to use yet another library to assist with loading your primary library.

这篇关于如何知道JQuery是否已完成加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:12