Find()的Javascript代码优化 [英] Javascript code optimization for Find()

查看:63
本文介绍了Find()的Javascript代码优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有c#代码在SQL中运行查询并返回大约2000行。然后创建Treeview控件并添加我的主页面。这几乎是立即完成的,这很好。

I have c# code that runs a query in SQL and returns roughly 2000 rows. Then a Treeview control is created and added the my main page. This is done almost instantly, which is good.

var orgId = $('select[name="ctl00$PageContent$FunctionsDropDownList"] option:selected').val();
        if (!orgId) {
            return false;
        }
        //calls serverside get data
        //This line happens quickly
        $('#ctl00_PageContent_HiddenRulesDialogTriggerButton').click();

        //This part takes about 10-15 minutes to finally get to the true
        var i = setInterval(function () {
            if ($('#ctl00_PageContent_treeview').find('table').length > 0)
            {
                clearInterval(i);
                StartDialog();
                return false;
            }
        });

因此需要大约10-15分钟才能达到 clearInterval(i) 。如果是, i = 978 。不知道为什么需要这么长时间。可能 find()真的很慢。有人推荐替代方案吗?

So it takes about 10-15 minutes to hit the clearInterval(i). When it does, i = 978. Not sure why it would take so long. Possibly the find() is really slow. Does anyone recommend an alternative?

编辑

推荐答案

问题可能是您在没有第二个参数的情况下调用setInterval(时间间隔)

The problem is probably the fact that you are calling setInterval without the second argument (time interval)

让我们来看看你的代码似乎在做什么。

Let's look at what your code seems to do.


  1. 查询后端,拉出构建树视图所需的数据。这是快速完成的。

  2. 异步构建树。

  3. 在树构建时,继续使用find()进行检查以查看它是否是准备好。

一些问题。


  1. 与非DOM数据操作相比,所有DOM查询都相当慢。所以是的,find()不是最快的函数,因为它从你指定的父对象开始搜索整个DOM并返回它找到的对象。

  2. 如果你只运行setInterval像你这样的一个论点:

代码:

var timer_id = setInterval(function() {
    ...code here...
});

...我认为它每毫秒执行一次。我用这段代码对此进行了测试:

...I think it executes every millisecond. I've tested this with this code:

var k = 1;
var i = setInterval(function () {
    if (k < 100)
    {
        k += 1;
    } else {
        clearInterval(i);
        window.alert('Finished!');
    }
//No second argument
});

......几乎立即完成。

...and it finished almost instantly.

所以我猜它变得如此缓慢,因为该程序每秒数百次触发昂贵的DOM搜索。解决方案是:

So I'm guessing it is going so slow because the program is firing a costly DOM search hundreds of times per second. The solutions are:


  1. 提供在树构建结束时执行任何操作的函数作为异步构建函数的回调。通过这种方式,您无需检查。

  2. 尝试为setInterval提供一个时间间隔,看看它是否通过释放程序来构建树而不是重复检查来解决您的问题:

代码:

var i = setInterval(function () {
    if ($('#ctl00_PageContent_treeview').find('table').length > 0)
    {
        clearInterval(i);
        StartDialog();
        return false;
    }
//Once per second
},1000);

回调是更好的做法,但提供时间间隔也可能有效。

A callback would be better practice but supplying the time interval will probably work too.

这篇关于Find()的Javascript代码优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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