js 性能優化不外乎從三個角度入手:css
首先要避免沒必要要的冗餘代碼,包括沒必要要的閉包、沒必要要的變量與函數聲明、沒必要要的模塊分割等。前端
好比:java
// 低效的實現 const urlParams = (() => { const params = {}; if (location.search) { location.search.slice(1).split('&').forEach(item => { const arr = item.split('='); params[arr[0]] = arr[1] || ''; }); } return params; })(); // 更高效的實現 const urlParams = {}; if (location.search) { location.search.slice(1).split('&').forEach(item => { const arr = item.split('='); urlParams[arr[0]] = arr[1] || ''; }); }
其次是要避免使用沒必要要的第三方庫,由於通常第三方庫都很大,功能比較多,在條件容許的狀況下,儘可能少用。python
好比:jquery
const users = [ { user: 'barney', age: 36, active: true }, { user: 'fred', age: 40, active: false }, { user: 'pebbles', age: 1, active: true }, ]; // 使用 lodash import _ from 'lodash'; const user = _.find(users, { age: 1, active: true }); // 不使用 lodash const user = users.find(item => item.age === 1 && item.active === true);
還好比:webpack
css
動畫替代原有的 js
動畫的解決方案本質上講,這些都是從開發者編碼的角度來優化的,但這種方式也是頗有限的,由於不少時候咱們不得不大量的使用第三方庫,來提高開發效率。git
如今前端打包基本上都會用 webpack,但 webpack
打包以後的文件會產生不少冗餘代碼,這會致使 js
性能下降。github
若是在打包文件的性能上有特別需求的小夥伴,能夠使用 rollup,詳細使用與對比能夠參考這裏 webpack 以外的另外一種選擇:rollup.web
js
自己是沒有像 python
同樣的預編譯功能,更沒有像 java
同樣的編譯功能,因此,這裏所說的 js 代碼預編譯
只是經過工具實現的相似功能而已。npm
這就要提到 prepack 了,它的思路大體是這樣:
把不依賴外部環境的邏輯提早進行運算,並把運算結果替換到相應的源碼處,而後從源碼中移除這段邏輯。
npm install -g prepack
prepack script.js
prepack script.js --out script-processed.js
源代碼
(() => { const secondsOfOneDay = 24 * 60 * 60; window.getSecondsOfDays = days => days * secondsOfOneDay; })();
編譯後的代碼
(function () { var _$0 = this; var _1 = days => { return days * 86400; }; _$0.getSecondsOfDays = _1; }).call(this);
0.2.51
,還一直在開發中,不少功能都尚未實現,包括模塊輸入輸出的優化更多博客,查看 https://github.com/senntyou/blogs
版權聲明:自由轉載-非商用-非衍生-保持署名(創意共享3.0許可證)