對於前端的優化接觸的太少了,平時在pc端上感受正常,可是到了移動端,時間一長就不行了。今天說說html中ul的優化問題,我給出了一種傳統的寫法(耗時的),一種優化的寫法.
模擬一種業務流程吧,相似留言牆,你們留言後,要將留言顯示在留言牆上面。
開始咱們的代碼編寫吧
若是在平時我會這樣寫,可是假如我接收了一百萬條數據,代碼以下:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>沒有進行性能優化的案例</title> </head> <body> <div id="divElement" style="height:200px;overflow-y:scroll;"></div> <script> var List = function(container,items,itemHeight){ this.container = container; this.items = items; this.itemHeight = itemHeight; this.init(); this.update(); } List.prototype.init = function(){ //建立一個ul this.ul = document.createElement("ul"); this.ul.style.position = "relative"; //將元素添加到div中 this.container.appendChild(this.ul); } List.prototype.update = function(){ for(var i = 0; i < this.items.length; i++){ var liTag = document.createElement("li"); liTag.textContent = this.items[i] this.ul.appendChild(liTag); } } //模擬數據 var array = []; for(var i = 0; i < 1000000; i++){ array.push(i) } new List(document.getElementById("divElement"),array,16); </script> </body> </html>
整整使用了大約一分鐘,個人天啊,我想你們早已散去,能夠看到時間都花在了Rendering中,而且要等全部的li都渲染好了以後,纔會顯示,用戶體驗感極差.
優化方案就是減小Rendering.設定數量合適的li標籤,根據位置調整li的內容與樣式前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>性能優化</title> </head> <body> <div>List的性能優化</div><br> <br> <br> <div id="divElement" style="height:200px;overflow-y: scroll;"></div> <script> var List = function(container,items,itemHeight){ this.container = container; this.items = items; this.itemHeight = itemHeight; this.init(); this.update(); } List.prototype.init = function(){ //建立一個ul標籤 this.ul = document.createElement("ul"); this.ul.style.position = "relative"; //獲取的顯示的高度內能夠最多顯示多少條數據 var len = this._maxLength(); var html = ""; for(var i = 0; i < len; i++){ html += "<li>" + this.items[i] + "</li>"; } this.ul.innerHTML = html this.container.appendChild(this.ul); var self = this; this.container.addEventListener("scroll",function(){ self.update() }) } List.prototype._maxLength = function(){ var h = this.container.offsetHeight; return Math.min(Math.ceil(h / this.itemHeight),this.itemHeight); } List.prototype.update = function(){ //計算出ul的高度 this.ul.style.height = this.items.length * this.itemHeight + "px"; this.ul.style.margin = 0; //計算出滑動條目前位置前有多少個li標籤 var start = Math.floor(this.container.scrollTop / this.itemHeight); console.log("start:",start) //得到全部的子節點 var items = this.ul.children; //得到長度 var len = this._maxLength(); for(var i = 0; i < len; i++){ var item = items[i]; if(!item){ item = items[i] || document.createElement("li"); this.ul.appendChild(item); } var index = start + i; item.innerHTML = this.items[index]; item.style.top = this.itemHeight * (index) + "px"; item.style.position = "absolute"; } } //模擬數據 var array = []; for(var i = 0; i < 1000000; i ++){ array.push(i) } var list = new List(document.getElementById("divElement"),array,16); </script> </body> </html>
再來看一眼性能圖
性能優化
一樣的寫法這樣速度直接提升了20倍.app