Как эффективно создавать фрагмент документа [дубликат]

Вы можете использовать эту пользовательскую библиотеку (написанную с помощью Promise) для выполнения удаленного вызова.

function $http(apiConfig) {
    return new Promise(function (resolve, reject) {
        var client = new XMLHttpRequest();
        client.open(apiConfig.method, apiConfig.url);
        client.send();
        client.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                // Performs the function "resolve" when this.status is equal to 2xx.
                // Your logic here.
                resolve(this.response);
            }
            else {
                // Performs the function "reject" when this.status is different than 2xx.
                reject(this.statusText);
            }
        };
        client.onerror = function () {
            reject(this.statusText);
        };
    });
}

Пример простого использования:

$http({
    method: 'get',
    url: 'google.com'
}).then(function(response) {
    console.log(response);
}, function(error) {
    console.log(error)
});
0
задан user1157751 26 September 2014 в 22:53
поделиться

2 ответа

Попробуйте обработать полученные данные постепенно.

В приведенном ниже фрагменте элементы, сгенерированные в блоках 250, в основном с использованием jQuery offferred.notify () и deferred.progress () .

Когда все 10000 обработанных объектов, deferred объект resolved с коллекцией из 10 000 элементов. Затем элементы добавляются к document при одном вызове .html() в обратном вызове отложен. Then () .done(); .fail() callback cast как null.

В качестве альтернативы, можно добавить элементы к document в блоках 250, в пределах deferred.progress обратного вызова; вместо [1]

setTimeout используется для предотвращения «замораживания веб-браузера».

g4]
$(function() {
// 10k items 
var arr = $.map(new Array(10000), function(v, k) {
  return v === undefined ? k : null
});
  
var len = arr.length;
var dfd = new $.Deferred();
// collection of items processed at `for` loop in blocks of 250
var fragment = [];
var redraw = function() {
  for (i = 0 ; i < 250; i++)
    {
        // configurationVariableChart.row.add(
        // $(
        fragment.push('<tr>' +
                '<td>' + arr[i] + '</td>' +
            '</tr>')
        // )[0]);
    };
    arr.splice(0, 250);
    console.log(fragment, arr, arr.length);
    return dfd.notify([arr, fragment])
};

$.when(redraw())
// `done` callbacks
.then(function(data) {
  $("#results").html(data.join(","));
  delete fragment;
}
  // `fail` callbacks      
 , null
  // `progress` callbacks
 , function(data) {
  // log ,  display `progress` of tasks
     console.log(data);
     $("progress").val(data[1].length);
     $("output:first").text(Math.floor(data[1].length / 100) + "%");
     $("output:last").text(data[1].length +" of "+ len + " items processed");
     $("#results").html("processing data...");
     if (data[0].length) {
         var s = setTimeout(function() {
             redraw()
         }, 100)
     } else {
       clearTimeout(s);
       dfd.resolve(data[1]);
     }
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<progress min="0" max="10000"></progress><output for="progress"></output>
<output for="progress"></output><br />
<table id="results"></table>
jsfiddle http://jsfiddle.net/guest271314/ess28zLh/

3
ответ дан guest271314 26 August 2018 в 11:18
поделиться
1
ответ дан Daniel Roseman 26 August 2018 в 11:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: