简体   繁体   English

jQuery:如何改进此代码?

[英]jQuery: How can I improve this code?

I have this tap event in an iOS app that I'm developing with PhoneGap. 我正在使用PhoneGap开发的iOS应用程序中有此点击事件。 When I click on the left arrow, it finds the desired content and retrieves it from a JSON file. 当我单击左箭头时,它会找到所需的内容并从JSON文件中检索它。 It then displays those results on the screen. 然后,将这些结果显示在屏幕上。

How can I improve this? 我该如何改善? There's a bit of lag... I know that some of the lag is attributed to the 300ms delay (which fastclick.js and other libraries could resolve), but what else can I do to restructure this code and make it more snappy? 有点滞后...我知道有些滞后是由于300毫秒的延迟(fastclick.js和其他库可以解决的),但是我还能做些什么来重新构造此代码并使它更加生动? I need it to respond quickly. 我需要它迅速做出反应。 Thanks! 谢谢!

// PREVIOUS DAYS
    $('.left-arrow').on("tap", function() {
        dateArrayIndex--;
        todaysDate = morehShiur[dateArrayIndex]['date'];
        todaysContent = morehShiur[dateArrayIndex]['description'];
        $('.date').text(todaysDate);
        var path = window.location.href.replace('index.html', '');
        $.getJSON(path + "data/heb-text/" + todaysContent, function(data) {
            $('.title').empty();
            $('ol').empty();
            $('.title').append(data['title']);
            for (var i = 0; i < data.content.length; ++i) {
                $('ol').append('<li>' + data.content[i]['content'] + '</li>');
            }
            $("html, body").animate({ scrollTop: 0 }, 0);
        });
    });

I agree with the comments that your lag is likely related to doing an ajax call. 我同意您的滞后可能与进行ajax调用有关的评论。 However, there are a few things you can do to this code that will potentially improve things. 但是,您可以对此代码执行一些操作,这些操作有可能会改善某些情况。

  • You can scope or cache your selectors like $('.date') . 您可以像$('.date')那样限制或缓存选择器。 DOM lookups are expensive. DOM查找非常昂贵。
  • You can select multiple things using a , so your empty becomes: $('.title, ol').empty() 您可以使用来选择多个项目,因此您的空白变为: $('.title, ol').empty()
  • You can build HTML once in memory and then append to the DOM rather than appending with each iteration in your for loop. 您可以在内存中构建一次HTML, 然后将其附加到DOM,而不是在for循环中附加每次迭代。

As an example of the last point: 作为最后一点的示例:

var $liArray = $('<div/>');
for (var i = 0; i < data.content.length; ++i) {
  $liArray.append('<li>Hello</li>');
}
$("ol").append($liArray);

You can cache the server data at the client to avoid repeated server calls. 您可以在客户端缓存服务器数据,以避免重复的服务器调用。 Also you can pre-fetch 3 days of data(current date, previous date and next date). 您还可以预取3天的数据(当前日期,上一个日期和下一个日期)。 So the user does not see the delay for the current date. 因此,用户看不到当前日期的延迟。 But in the background you are fetching data for other days. 但是在后台,您将要提取其他日期的数据。

You can try libraries like http://amplifyjs.com/ for request caching. 您可以尝试使用http://amplifyjs.com/之类的库进行请求缓存。

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

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