Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Optimize JavaScript execution and parse time us...

chph
September 30, 2016

Optimize JavaScript execution and parse time using optimize-js

chph

September 30, 2016
Tweet

More Decks by chph

Other Decks in Technology

Transcript

  1. optimize-js https://github.com/nolanlawson/optimize-js Optimize a JavaScript file for faster initial load

    by wrapping eagerly-invoked functions 2016/9/18 建⽴的專案 2016/9/20 釋出 v1.0.1 最新版 作者:Nolan Lawson Web Platform PM @ Microsoft Edge 
  2. ⽤法: 
 optimize-js input.js > output.js  範例輸出 !(function (){})()

    function runIt(fun){ fun() } runIt((function (){})) 範例輸⼊ !function (){}() function runIt(fun){ fun() } runIt(function (){})
  3. jQuery v3.1.0 
 Minified v.s. Min+Optimized    

     3FGFSFODFIUUQTHJUIVCDPNOPMBOMBXTPOPQUJNJ[FKTCFODINBSLPWFSWJFX NT
 NT NT NT NT
 NT NT
 NT
  4. 無痛安裝 React •使⽤ Facebook 出品的 Create React App •https://github.com/facebookincubator/create-react-app $

    npm install -g create-react-app $ create-react-app afu-react-test-app $ cd afu-react-test-app/ $ npm start 
  5. 無痛安裝 React (續) •開發版本本地端網址 • http://localhost:3000/ ! •打包發佈版本 $ npm

    run build ! 47.18 KB build/static/js/main.c9763294.js 289 B build/static/css/main.9a0fe4f1.css 
  6. 以 PHP 7 內建 web server 
 佈署網站 $ php

    -S localhost:8888 PHP 7.1.0-dev Development Server started at Fri Sep 30 01:41:41 2016 Listening on http://localhost:8888 Document root is /Users/citeair/lab/afu-react-test-app/build Press Ctrl-C to quit. [Fri Sep 30 01:41:48 2016] ::1:58054 [200]: / [Fri Sep 30 01:41:48 2016] ::1:58055 [200]: /static/css/main.9a0fe4f1.css [Fri Sep 30 01:41:48 2016] ::1:58056 [200]: /static/js/main.c9763294.js 
  7. 原理? •多數 JavaScript engine 會做 lazy parsing optimization •根據經驗法則,⼤部分的 function

    永遠不會或是稍後才被執⾏ •可能不適⽤於 framework-based application,因為打包過的 code 都是 必定會執⾏的 /* 直到 f 被呼叫時才剖析 function 內容 */ function f () { … } •若外部 scope 有⽤變數參照 f,f 會被解析兩次 •優化版,不做 lazy parsing (function f () {...})() 
  8. demo by @bmaurer function immutable () { (function (global, factory)

    { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); }(this, function () { ... }); }  71BSTF-B[Z
 NT 71BSTF-B[Z
 NT IUUQTHJUIVCDPNSPMMVQSPMMVQQVMMJTTVFDPNNFOU
  9. demo by @bmaurer function immutableOptimize () { (function (global, factory)

    { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); }(this, (function () { ... })); }  71BSTF-B[Z
 NT IUUQTHJUIVCDPNSPMMVQSPMMVQQVMMJTTVFDPNNFOU
  10. 有得必有失 •jQuery v3.1.0:30450 -> 30524 bytes,增加 74 bytes •Lodash v4.15.0:

    24528 -> 24577 bytes,增加 49 bytes •React v15.3.2 + Create React App:160518 -> 160609 bytes,增加 91 bytes