Skip to content Skip to sidebar Skip to footer

Jquery Sort Causing Ios Safari To Freeze

I have a page that is using jQuery to load an XML file, which I'm then outputting the contents of to the page. Recently I added a sorting function to the output which is causing a

Solution 1:

Every time you do $(a) it will perform a very complex set of operations, so you better cache it. Also, you don't need the Title if System is different. This version should speed it up a bit:

videoGames.sort(function (a, b) {
    var first = $(a);
    var second = $(b);
    var firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();
    var secondSystem = (second.find("console").text() + " " + second.find("version").text()).toLowerCase();

    if (firstSystem != secondSystem) {
        if (firstSystem > secondSystem) {
            return1;
        } else {
            return -1;
        }
    } else {
        var firstTitle = first.find('title').text().toLowerCase();
        var secondTitle = second.find('title').text().toLowerCase();

        if (firstTitle > secondTitle) {
            return1;
        } elseif (secondTitle < firstTitle) {
            return -1;
        }
    }
    return0;
});

You could also cache the values in the object

Then, instead of:

var firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();

Do:

var firstSystem = first.data('system');
if (!firstSystem) {
    firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();
    first.data('system') = firstSystem;
}

Solution 2:

You should move any selectors calls like this:

var firstTitle = $(a).find('title').text().toLowerCase();

out from the comparator function. The comparator function is supposed to be lightweight.

Either use children(), next() and the like or scan you set once and create an array of keys upfront and then sort it using those keys.

The comparator function will be called 2n * ln(n) times (depends on algorithm used) where n is a number of elements in a set. So your code does the same expensive calculations twice at least.

Post a Comment for "Jquery Sort Causing Ios Safari To Freeze"