2017-02-13 111 views
0

我開發iOS應用程序,但加載項下面的代碼動態似乎並不工作延遲加載問題的Safari&Wkwebview

var offset_c = 5; 
     $(window).scroll(function(){ 
      var content = document.getElementById("wrap"); 
      var content_height = content.offsetHeight; 
      var yoffset = window.pageYOffset; 
      var scrolloffset = yoffset + window.innerHeight; 
      if(scrolloffset >= content_height){  
        $.post("ajax/products_ajax.php?offset",{offset:offset_c},function(data){ 
         $(".products").append(data); 
         offset_c = offset_c + 5; 
         });    
       } 
    }); 

上面的代碼確實是什麼,它會發送Ajax請求罰款但它會反覆加載接下來的10個產品(5-15)大約5次。沒有真正解決代碼問題。

回答

1

您的$.post()代碼在滾動時被觸發。這意味着當用戶在您的網站/應用中滾動(或滑動)時,它會不斷被解僱。這就是爲什麼它會重複觸發5次或更多次。你應該「消除」滾動處理程序,以確保它不會繼續通話。目前的代碼對性能也有很大的影響。在David Walsh blog是件不錯的防抖代碼:

// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. If `immediate` is passed, trigger the function on the 
// leading edge, instead of the trailing. 
function debounce(func, wait, immediate) { 
    var timeout; 
    return function() { 
    var context = this, args = arguments; 
    var later = function() { 
     timeout = null; 
     if (!immediate) func.apply(context, args); 
    }; 
    var callNow = immediate && !timeout; 
    clearTimeout(timeout); 
    timeout = setTimeout(later, wait); 
    if (callNow) func.apply(context, args); 
    }; 
}; 

這將是這個樣子在你的榜樣:

var efficientScrollHandler = debounce(function() { 
    // All the taxing stuff you do 
    // Like $.post() and stuff 
}, 250); // <-- gets triggered maximum one time per 250ms 

$(window).scroll(efficientScrollHandler); 
+0

太謝謝你了。這使得純粹的感覺和令人驚訝的工作。 –