0

i simplified my issue as the following: I have a huge array of elements and, for each of them, i need to create a div. This causes a browser freeze or even worse a popup asking to stop the script.

var fruits = ["0"]; 
for ( var i = 1; i < 2000; i ++){
    fruits.push(i);
}

function qweqwe(fruits) {
    var ida = fruits.shift();
    if (ida) {
        console.log(ida);
        $('#0').clone(true).attr('id', ida).insertAfter($('.asd:last'));
        qweqwe(fruits);
    }
}
$( "#butt" ).click(function() {
qweqwe(fruits);
});

Is there any way to avoid it? or any workaround? any way to create 50 elements at a time maybe? i created a jsfiddle to better explain my issue http://jsfiddle.net/b7dewtsk/1/ thanks in advance regards

Gotrekk
  • 494
  • 2
  • 15

2 Answers2

0

You can think of it like a social media; there's lots of content to be displayed but if all the content were to be fetched at the same time, things would go south.

Fetch and display a subset of the data, then when the users scrolls down then you can perform an AJAX to fetch the next subset of data to be added. You can even fetch the subset right away and append it when the scrolling begins, so your data is ready when needed.

There's no point in querying the entire database anyway if the user's only going to need to see the first 5% of it.

Edit

If you're 100% sure you want the entire content of the database table then I'd go with @Yury Tarabanko's point since working with a string is way more lightweight in comparison to performing an add operation n times.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • this sounds like a really good interpretation/solution... any tips on how to do it? :D – Gotrekk Nov 21 '14 at 10:59
  • [This](http://stackoverflow.com/questions/14035180/jquery-load-more-data-on-scroll) looks like a pretty neat solution or somewhat close to it, I'm sure there are lots of alternatives around :) – Jonast92 Nov 21 '14 at 11:04
  • 1
    yes, i think @Yury Tarabanko's solution should work for now. Thanks a lot for your idea tho! It's always useful to keep an alternative in mind! – Gotrekk Nov 21 '14 at 11:11
0

You can actually create a large html string and append it to the DOM at once.

function showFruits(){
    var html = [];
    fruits.forEach(function(fruit) {
        html.push('<div id="', fruit, '" class="asd">qwe</div>');
    });
    $(html.join('')).insertAfter('.asd');
}

$( "#butt" ).click(showFruits);

Demo.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98