前端最佳化方法集錦--bigrender,集錦--bigrender
- 如何加快首屏內容展現速度
思路是一次性讀出所有文檔,但是將不需要第一屏展現的內容放在textarea標籤中,判斷螢幕滾動,當該內容的容器出現在可視範圍,則取出textarea標籤中的內容,渲染到dom樹中。
var topics = {};jQuery.Topic = function(id) { var callbacks, method, topic = id && topics[id]; if (!topic) { callbacks = jQuery.Callbacks(); topic = { publish: callbacks.fire, subscribe: callbacks.add, unsubscribe: callbacks.remove }; if (id) { topics[id] = topic; } } return topic;};(function($) { $.fn.bigrender = function(opts) { var winHeight = document.documentElement.clientHeight; var sum = 0; var count = 0; var flash = []; // 'class' 是textarea父節點的類;'textarea' 是textarea標籤的類;'threshold'是距離進入螢幕還有150像素就開始渲染;'remove'是否刪除textarea標籤 options = $.extend({ 'class': '.render', 'textarea': 'textarea', 'threshold': 150, 'remove': true }, opts); $brenders = $(options['class']); // 渲染首屏的內容 initBigrender(); // 綁定捲軸事件 scrollDisplay(); // 函數定義 function initBigrender() { $brenders.each(function(n, object) { sum++; if (isRender($(this))) { display($(this)); count++; flash[n] = true; } else { flash[n] = false; } }); } // 判斷時候需要渲染 function isRender(object) { offsetTop = object.offset().top; ojh = object.outerHeight(true); st = Math.max(document.body.scrollTop || document.documentElement.scrollTop); if (offsetTop + ojh + options.threshold >= st && offsetTop - options.threshold < (st + winHeight)) { return true; } else return false; } // 渲染textarea內的html代碼 function display(object) { $display = object.find(options.textarea).eq(0); if (options.remove) { object.append($display.val()); $display.remove(); } else { object.append($display.val()); } $.Topic('dom_render').publish(object); } // 螢幕綁定捲軸事件,當待渲染的內容進入可視螢幕就觸發isRender函數 function scrollDisplay() { $(window).scroll(function(event) { event.preventDefault(); if (count < sum) { $brenders.each(function(n, object) { if (flash[n] === false) { if (isRender($(this))) { display($(this)); count++; flash[n] = true; } else { flash[n] = false; } } }); } }); } };})(jQuery);
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。