I have this jquery function which I found on a tutorial site that takes in a csv file input and tablifies it. I tried giving in a large csv file(10,000KB) and my browser crashes. I saw there's a parser library called papa to handle this but is there any other approach to keep my browser from crashing while doing this?
Here's the relevant code:-
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='mytable' class='table table-striped table-bordered'/>");
var rows = e.target.result.split("\n");
text1=e.target.result;
var csvString = $.trim(text1);
var csvRows = csvString.split(/\n/);
var csvHeaders = csvRows.shift().split(';');
var headerstr=String(csvHeaders);
var count = (headerstr.match(/,/g) || []).length+1;
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
for (var j = 0; j < count; j++) {
if(cells[j]){
var cell = $("<td/>");
cell.html(cells[j]);
}
else{
var cell = $("<td class='info'/>");
cell.html("empty");}
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
});
How do I implement this functionality without crashing my browser? Thanks in advance.
vars inside the for loop are particularly bad.vars inside the loop will fix this. What I was saying is that doing that is particularly taxing on memory. You are doing a lot of other stuff that's not memory and CPU efficient. Repeatedly building the same HTML structure inside the loop is also bad. Try building it outside of the loop and only inject the data inside it, then append it to the DOM. Also try to add batches of table lines at a time, not one at a time. jQuery knows$(element).append([list of nodes])and optimizes it using document fragments.