使用script_queue进行JS函数时的执行顺序 [英] execution order when using a script_queue for JS functions

查看:82
本文介绍了使用script_queue进行JS函数时的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的工作地点,我们在site.master页面中定义了一个脚本队列

at our work place, we define a script queue in our site.master page

<script>
    // append functions to this array that will be executed after js dependencies have loaded
    var script_queue = [];
</script>

然后我们将javascript函数推送到此script_queue来执行它们。我遇到了一个问题,比如我有两个功能

And then we push javascript functions to this script_queue to execute them. I am running into a problem, say I have 2 functions

<script type="text/javascript">
// THIS IS FUNCTION 1
       script_queue.push(function() {

           // set the width of the thumbnail list to the sum of all the li widths
           var thumbsWidth = 0;
           $('#oneClipPlaylist li').each(func
     …
}
</script>


  script_queue.push(function() {
     // THIS IS FUNCTION 2
        var allInputs = $('fieldset.categories input');
        var categoryInputs = $('fieldset.categories input').not('#categoryAll');
        var categoryAllInput = $('#categoryAll');

        allInputs.click(function() {

            var checkbox = $(this);

这是队列的处理方式:

<script> 
    (function () { 
        for (var i in script_queue) { 
            script_queue[i](); 
        } 
    } ());
</script>

何我确保在功能2之前执行功能1吗?因为我遇到的问题是我的函数2在函数1之前执行并且结果不正确

How do I make sure that function 1 is executed before function 2? Because I am running into a problem that my function 2 executed before function 1 and the results are incorrect

推荐答案

命名第二个函数和不要排队,然后在第一个被放入队列的函数结束时调用第二个函数。

Name the second function and don't queue it up, then call the second function at the end of the first function that is getting put in the queue.

<script type="text/javascript">
// THIS IS FUNCTION 1
       script_queue.push(function() {

           // set the width of the thumbnail list to the sum of all the li widths
           var thumbsWidth = 0;
           $('#oneClipPlaylist li').each(func
     …
    secondFunc();
}

function secondFunc() {
// THIS IS FUNCTION 2
        var allInputs = $('fieldset.categories input');
        var categoryInputs = $('fieldset.categories input').not('#categoryAll');
        var categoryAllInput = $('#categoryAll');

        allInputs.click(function() {

            var checkbox = $(this);

    ...
}
</script>

这篇关于使用script_queue进行JS函数时的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆