简体   繁体   中英

jQuery: How can I improve this code?

I have this tap event in an iOS app that I'm developing with PhoneGap. When I click on the left arrow, it finds the desired content and retrieves it from a JSON file. 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? 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. 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') . DOM lookups are expensive.
  • You can select multiple things using a , so your empty becomes: $('.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.

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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