是否可以在加载jQuery之前预先注册处理程序?

时间:2014-07-23 11:26:34

标签: javascript jquery asynchronous

jQuery在页面后期加载的情况,但依赖于jQuery可用的javascript在之前加载 jQuery是一种非常常见的场景,特别是如果你遵循将脚本放得更接近的做法</body>

所以基本上我想离开这个:

<script>
  someFunctionThatUsesLateJQuery(){ [code that relies on jQuery] }
</script>

...

<script src="jquery.js"></script>
<script>
  $(function(){
    someFunctionThatUsesLateJQuery();
  });
</script>

对于这样的事情:

<script>
  _$.ready(function(){ [code that relies on jQuery] });
</script>

...

<script src="jquery.js"></script>

就像异步统计跟踪(álaGoogleAnalytics)一样,有没有什么可以让你注册javascript函数调用,一旦加载jQuery就会执行而不会出现可怕的$ is undefined错误?

我的意思是发生这种情况没有注册和取消注销超时/间隔。

有没有/有没有可能在jQuery中添加某种预注册变量,它会在加载后识别和处理?

用例:

值得注意的是,我所获得的具体用例是一个嵌入式JS小部件,我希望在<script>位置的场景中进行一些DOM操作,因此具有非常真实的在</body>附近发生jQuery加载的情况下加载jQuery之前出现的可能性。

然后我不想让用户进一步负担,要求他们在代码执行的正确位置注册一个特定的函数调用(这将取决于他们的实现)......我想要“只是工作“

4 个答案:

答案 0 :(得分:0)

当所有函数调用都转移到数据属性时,您可以尝试使用常见且流行的解决方案。然后,当加载jQuery时,您将抛出具有此类属性的所有DOM元素并运行此函数。 即而不是函数调用,你添加data-type='load' data-function='YourNamespace.yourFunctionName',在window.load事件之后,你按$('[data-type="load"]')选择所有元素,迭代它们,并执行函数调用。


UPD:猜猜,异步函数排队模式可能对以下内容有用: What's the name of Google Analytics async design pattern and where is it used?

答案 1 :(得分:0)

根据建议here by rich.okelly,你可以试试这个:

(function() {
    var runMyCode = function($) {
        // jquery-dependent code here
        $("#foo").data('bar', true);
    };

    var timer = function() {
        if (window.jQuery && window.jQuery.ui) {
            runMyCode(window.jQuery);
        } else {
            window.setTimeout(timer, 100);
        }
    };
    timer();
})();

我还发现了一个更复杂的解决方案,但我个人更喜欢上述解决方案而不是this solution

不超时更新

<script>
var runMyCode = function($) {
    // jquery-dependent code here
    $("#foo").data('bar', true);
};
</script>

...

<script src="jquery.js"></script>
<script>
    $(function(){
        runMyCode(window.jQuery);
    });
</script>

答案 2 :(得分:0)

如果你注入jQuery脚本include,那么你可以监听onload事件。

function loadJS(url, onloadCallback, elId){
//Inject script include into HEAD
    var scriptEl = document.createElement('script');
    scriptEl.type = 'text/javascript';
    scriptEl.src = url;
    if(elId)scriptEl.id = elId;
    document.getElementsByTagName('head')[0].appendChild(scriptEl);

    if(onloadCallback){
        scriptEl.onload = scriptEl.onreadystatechange = function(){
            if(!scriptEl.readyState || (scriptEl.readyState === 'complete' || scriptEl.readyState === 'loaded')){
                onloadCallback();
                scriptEl.onload = scriptEl.onreadystatechange = null;
            }
        }
    }
}

loadJS("http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", function(){
    console.log( window.$ );
});

答案 3 :(得分:0)

也许我完全不理解用例,但RequireJS听起来对你来说可能是一个不错的选择:

https://github.com/requirejs/example-jquery-shim

define(["jquery", "jquery.alpha", "jquery.beta"], function($) {
    //the jquery.alpha.js and jquery.beta.js plugins have been loaded.
    $(function() {
        $('body').alpha().beta();
    });
});