首頁  >  文章  >  web前端  >  關於如何優化jQuery的實例詳解

關於如何優化jQuery的實例詳解

零下一度
零下一度原創
2017-06-17 17:46:081221瀏覽

在最近的一個jquery外掛程式中,我使用到了jQuery中的resize()方法來偵測使用者調整瀏覽器視窗並執行相關程式碼。

我注意到resize window時各個瀏覽器的效能消耗不一。

IE、Safari、Chrome在調整視窗變化中一直在執行resize事件

Opera則在這個過程中發生了很多次resize事件,但在結束調整時執行。

Firefox則是只在調整結束後才會執行事件。

而我們想要的明顯是在結束調整之後才執行事件。幸運的是我們可以透過以下幾種方法來調整。

jQuery惰性外掛

jQuery throttle / debounce: Sometimes, less is more!

(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

使用方法:

function log( event ) {
  console.log( $(window).scrollTop(), event.timeStamp );
};

// Console logging happens on window scroll, WAAAY more often
// than you want it to.
$(window).scroll( log );

// Console logging happens on window scroll, but no more than
// once every 250ms.
$(window).scroll( $.throttle( 250, log ) );

// Note that in jQuery 1.4+ you can unbind by reference using
// either the throttled function, or the original function.
$(window).unbind( 'scroll', log );

JS程式碼

(function($,sr){

// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;

return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};

if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);

timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});

總結起來第一種簡單容易理解,第二種則是比較全面,程式碼也少,第三種也差不多。

javascript-resize-performance/

第二種:benalman.com/projects/jquery-throttle-debounce-plugin/

#第三種:www.paulirish. com/2009/throttled-smartresize-jquery-event-handler/

JavaScript程式碼:unscriptable.com/2009/03/20/debouncing-javascript-methods/

以後對於滾動、調整窗體大小等最好使用這種方法來減少JavaScript執行的次數。慎記。

以上是關於如何優化jQuery的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn