javascript 加快客户端数据表加载时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21601724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:17:24  来源:igfitidea点击:

Speeding up Datatables load time on client side

javascriptjquery-datatables

提问by Gaurav

I am using datatablejs on client side for displaying the database to client. I download the database from server initially using backbone indexeddb adapter and store it in indexedDB so as to support offline access to data. However, datatables take approx around 5 minutes to render 20,000 entries. This is my JS code:

我在客户端使用 datatablejs 向客户端显示数据库。我最初使用主干 indexeddb 适配器从服务器下载数据库并将其存储在 indexedDB 中,以支持对数据的离线访问。但是,数据表需要大约 5 分钟才能呈现 20,000 个条目。这是我的JS代码:

render_data: function(entity_collection) {
        //create table body in memory
        tbody = $('<tbody>');
        tbody.html('');

        //iterate over the collection, fill row template with each object 
        //and append the row to table
        entity_collection.each(function(model) {
            tbody.append(this.row_template(model.toJSON()));
        }, this);
        //put table body in DOM
        this.$('#list_table')
            .append(tbody);
        //initialize datatable lib on the table    
        this.$('#list_table')
            .dataTable();
        $("#loaderimg")
            .hide();
        $("#sort-helptext").show();
},

Table headers:

表头:

<script type="text/template" id="person_table_template"> 
    <tr> 
        <th>Id</th> 
        <th>Name</th> 
        <th>Father Name</th> 
        <th>Village</th> 
        <th>Group</th> 
        <th></th> 
    </tr> 
</script>

JSON which is converted to html:

转换为 html 的 JSON:

Object {
    age: 45, 
    father_name: "Jiyan Sah ", 
    gender: "F", 
    group: Object, 
    id: 10000000155392, 
    label: "Gangajali Devi (Sahila Rampur,Jiyan Sah )", 
    online_id: 10000000155392, 
    person_name: "Gangajali Devi ", 
    phone_no: "", 
    resource_uri: "/coco/api/v1/person/10000000155392/", 
    village: Object
}

Can anybody suggest about how to increase the performance of datatable?

有人可以建议如何提高数据表的性能吗?

回答by Evgeniy

Firstly, the is no need to append data on each iteration, you can do it once after loop.

首先,不需要在每次迭代时附加数据,您可以在循环后执行一次。

var tmp_str = '';

entity_collection.each(function(model) {
    tmp_str+=this.row_template(model.toJSON())
}, this);

tbody.append(tmp_str);

But to really speed-up the app i recommend you to change render way - now you render all data at once and have no information what part of information is watched but client. Lazy loading can help you - for eg. you render first 100 items, when page is scrolled to the bottom on the list you render + 100 and so on.

但是要真正加快应用程序的速度,我建议您更改渲染方式 - 现在您一次渲染所有数据并且不知道除了客户端之外的信息的哪些部分被观看。延迟加载可以帮助您 - 例如。您渲染前 100 个项目,当页面滚动到列表底部时,您渲染 + 100,依此类推。

If you need some code help let me know.

如果您需要一些代码帮助,请告诉我。

回答by orzechow

Try to build the datatable directly from your js object (see DataTables Example here) instead of building a DOM object first.

尝试直接从您的 js 对象构建数据表(请参阅此处的数据表示例),而不是先构建 DOM 对象。

Maybe datatablejs is faster in evaluating json arrays than in analysing such big DOM objects (and deleting most of it again)

也许 datatablejs 在评估 json 数组时比分析如此大的 DOM 对象(并再次删除大部分)更快

Going this way you can set "bDeferRender": truewhich will cause that datatablejs will only render visible rows giving you a huge speed boost (see the datatablejs features page)

通过这种方式,您可以设置"bDeferRender": true这将导致 datatablejs 仅呈现可见行,从而为您提供巨大的速度提升(请参阅datatablejs 功能页面

By using the js array initialization you lose HTML fallback for users without JavaScript of course - but I guess that's not your audience ;-)

通过使用 js 数组初始化,您当然会失去没有 JavaScript 的用户的 HTML 回退 - 但我想那不是您的受众;-)

Also take a look at disabling CSS height matchingThis could save you some rendering time.

另请查看禁用 CSS 高度匹配这可以为您节省一些渲染时间。

回答by Thorsten Artner 'Austria'

if you want speed improvement, write your own function with Javascript and not use Jquery.

如果您想提高速度,请使用 Javascript 编写自己的函数,而不是使用 Jquery。

!!!! Its faster to first append and then add. !!!!!

!!!首先追加然后添加更快。!!!!!!

use also cloneNode which is faster then document.createElement only create once and clone. Look at this and place in the html <body onload="alert (new Date().getTime()-b);">

还使用 cloneNode ,它比 document.createElement 只创建一次并克隆更快。看看这个并将其放在 html <body onload="alert (new Date().getTime()-b);">

it tooks 700 ms to generate a datatable with 20000 entries of course it depends on the machine and data reading

生成一个包含 20000 个条目的数据表需要 700 毫秒,当然这取决于机器和数据读取

 var a=new Date().getTime ();
 var table_master=document.createElement ("table");
 var tbody_master=document.createElement ("tbody");
 var tr_master=document.createElement ("tr");
 var td_master=document.createElement ("td");
 var i,u, tr, td;
 document.body.appendChild (table_master);
 table_master.appendChild (tbody_master);

 for (i=0;i<4000;i++)
        {
        tr=tr_master.cloneNode ();
        tbody_master.appendChild(tr);   // check what happens if you put this line after for operation , when you first add the cells with data to tr and then append to the tbody, that would slow down imense
        for (u=0;u<5;u++)
            {
            td=td_master.cloneNode();
            tr.appendChild (td);
            td.appendChild (document.createTextNode("hello"));
            }
        }

回答by Ravi_Mishra

Hey Brother Check this out this may help u -------

嘿兄弟 看看这个可能对你有帮助 -------

Client Side code -----

客户端代码 -----

$("#table-tripNote").dataTable({
                "oLanguage": {
                    "sZeroRecords": "No records to display",
                    "sSearch": "Search from all Records"
                },
                "bProcessing": true,
                "bServerSide": true,
                "bDestroy": true,
                "sAjaxSource": "frmTrip.aspx/GetMemberNotesByTrip",
                "sPaginationType": "full_numbers",
                "bDeferRender": true,
                "aoColumns":
                            [
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null
                            ],
                "fnServerData": function (sSource, aoData, fnCallback) {
                    $.ajax({
                        "dataType": 'json',
                        "contentType": "application/json; charset=utf-8",
                        "type": "GET",
                        "url": sSource,
                        "data": aoData,
                        "success":
                                                    function (msg) {

                                                        var json = jQuery.parseJSON(msg.d);
                                                        fnCallback(json);
                                                        $("#table-tripNote").show();
                                                    }
                    });
                }
            });

Server side code---

服务端代码---

[WebMethod()]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetMemberNotesByTrip(string sEcho, int iDisplayStart, int iDisplayLength)
{

    string rawSearch = HttpContext.Current.Request.Params["sSearch"].Trim();

    var whereClause = string.Empty;

    var filteredWhere = "1=1";

    var wrappedSearch = rawSearch.Trim();
    var Tempsb = new StringBuilder();

    Tempsb.Append("mbrid=" + MemberID);
    if (TripID != 0)
    {
        Tempsb.Append("and trpid=" + TripID);
    }
    else
        Tempsb.Append("and trpid=0");

    if (rawSearch.Length > 0)
    {
        Tempsb.Append("AND ( ISNULL(trpDate,'''') LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrFullName LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrPhone LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrRelationshipToMember LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR trpNote LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR clrOrganization LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(" OR trpIsGrievance LIKE ");
        Tempsb.Append("'%" + wrappedSearch + "%'");
        Tempsb.Append(")");
    }

    if (Tempsb.Length > 0)
        filteredWhere = Tempsb.ToString();

    string orderByClause = string.Empty;
    orderByClause = "trpDate desc";

    StringBuilder sb = new StringBuilder();
    sb.Append(Convert.ToInt32(HttpContext.Current.Request.Params["iSortCol_0"]));

    sb.Append(" ");

    sb.Append(HttpContext.Current.Request.Params["sSortDir_0"]);

    orderByClause = sb.ToString();

    if (!String.IsNullOrEmpty(orderByClause))
    {
        orderByClause = orderByClause.Replace("0", ", trpDate ");
        orderByClause = orderByClause.Replace("1", ", clrFullName ");
        orderByClause = orderByClause.Replace("2", ", clrPhone ");
        orderByClause = orderByClause.Replace("3", ", clrRelationshipToMember ");
        orderByClause = orderByClause.Replace("4", ", clrOrganization ");
        orderByClause = orderByClause.Replace("5", ", trpIsGrievance ");
        orderByClause = orderByClause.Replace("6", ", trpNote ");

        orderByClause = orderByClause.Remove(0, 1);
    }
    else
    {
        orderByClause = "pronID ASC";
    }

    DataSet ds = clsTrip.GetTripNotesMaster(filteredWhere, orderByClause, iDisplayLength, iDisplayStart, true);


    List<clsTrip> lstTripNotesGrv = new List<clsTrip>();
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        clsTrip lsttripNotes = new clsTrip();
        lsttripNotes.clrFullName = ds.Tables[0].Rows[i]["clrFullName"].ToString();

        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpDate"].ToString()))
            lsttripNotes.trpDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["trpDate"].ToString());
        else
            lsttripNotes.trpDate = DateTime.MinValue;

        lsttripNotes.clrPhone = ds.Tables[0].Rows[i]["clrPhone"].ToString();
        lsttripNotes.clrRelationshipToMember = ds.Tables[0].Rows[i]["clrRelationshipToMember"].ToString();
        lsttripNotes.clrOrganization = ds.Tables[0].Rows[i]["clrOrganization"].ToString();

        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString()))
            lsttripNotes.trpIsGrievance = Convert.ToBoolean(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString());
        else
            lsttripNotes.trpIsGrievance = false;
        lsttripNotes.trpNote = (ds.Tables[0].Rows[i]["trpNote"].ToString());

        lstTripNotesGrv.Add(lsttripNotes);
    }
    int TotalRec = Convert.ToInt32(ds.Tables[1].Rows[0][0]);

    var result = from c in lstTripNotesGrv
                 select new[] { 
                       //Convert.ToString(c.pronID),                               
                       c.trpDate !=null && c.trpDate!=DateTime.MinValue ? string.Format("{0:MMM d, yyyy}",c.trpDate):"-",
                       c.clrFullName.ToString(),
                       c.clrPhone.ToString(),
                       c.clrRelationshipToMember.ToString(),
                       c.clrOrganization.ToString(),
                       ( Convert.ToBoolean(c.trpIsGrievance)?"Yes":"No"),
                       c.trpNote
                   };

    JavaScriptSerializer jss = new JavaScriptSerializer();
    return jss.Serialize(new
    {
        sEcho,
        iTotalRecords = TotalRec,
        iTotalDisplayRecords = TotalRec,
        aaData = result
    });
}