繁体   English   中英

如何提高JavaScript性能/减少大型HTML页面的页面负载?

[英]How to improve JavaScript performance / reduce page load on a page with large HTML?

我们具有如下页面布局,其中jQuery点击处理程序可处理大量HTML元素(数千个DIV)。

布局是这样的:

在此处输入图片说明


导航栏至少包含2000个DIV和UL,LI(用于内容导航),并且我们将jQuery事件处理程序绑定到每个元素:

$('.navbar-item').click(function(){ 

  /* click handler */

});

加载花费了很多时间,并且在IE上的性能非常糟糕! 无论如何,我们可以改善它吗? 或任何替代设计来解决此问题?

您还可以在函数( http://api.jquery.com/on/ )上使用

例如:

$('div.navbar').on('click', '.navbar-item', function(){ 

  /* click handler */

});

您有许多提高表现的可能性

1.您可以在用户滚动并使用Ajax时加载div

2.使用.on.click动态添加监听器

例如,您可以加载一些div并检查滚动,使用James Padolsey的此功能,该功能适用​​于所有浏览器

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}


$(window).scroll(function() {
       // when the scroll is in bottom
       if($(window).scrollTop() + $(window).height() == getDocHeight()) {
           // use ajax to get more div
           $.ajax({
               url: "otherDivs.php", // page where you load div
               data { firstDiv : '10', secondDiv : '20'}, // parameters : To load div 10 to 20
               type: "POST"
           })
           .done(function( html ) {
               $( "body" ).append( html ); // html contain div 10 to 20
           });
       }
   });

这只是一些可以帮助您的方法

减少页面上的节点数。 仅立即加载用户需要的内容,当用户向下滚动或打开导航级别时(如果您有可折叠的树)则延迟加载。

如果单击处理程序对于更多项目相同,请使用:

$('.navbar-item').click(function(){ 

    /* click handler */

});

您可以这样做:

var functionNav = function(){
    /* click handler */
}

$('.navbar-item').on("click", functionNav)

如果功能相似,您还可以参数化功能以执行更多任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM