二〇一四年一月十六日
動態組裝JS組態
有夠繞舌的,今天的主題就是動態地將不同的JS合併成一個檔案,以增加頁面載入速度及減低對伺服器的請求數。
以下是半個月前的草稿,在這之前我在做回覆功能,再之前就是提示功能。不過那兩個要說明比較複雜,所以先來個簡單點的。
原理其實不難,只要有終點起點。中間的可以慢慢苦出來。
起點:
終點:
於是我花了大概三個小時苦了出來:
由於不同的需求會調用不同的模組,這個存在於Modules(array)裏面的js列表會不斷改變。因此需要將其serialize再利用md5算出檔名,最後將模組組合成一個檔案存起來下次使用。
以下是我抽取了某段核心部份供大家參考:
結果:
於是這樣我將二十多檔請求變成三個請求了!
PS: 手指好冷!不想打字了,先這樣吧。
以下是半個月前的草稿,在這之前我在做回覆功能,再之前就是提示功能。不過那兩個要說明比較複雜,所以先來個簡單點的。
起點:
1 2 3 4 5 6 7 | <script src="a.js ... <script src="b.js ... <script src="c.js ... <script src="d.js ... . . . |
1 | <script src="compiled_unique_identifier.js" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Modules +--------+ | a.js | | b.js | md5 checksum | c.js | +------------+ Request => | d.js | => | b5742ad... | | e.js | +------------+ | f.js | | | g.js | | +------------------------+ | h.js | Cache exists ------- Yes ---> | Cache date < MMax date |------No +--------+ | +------------------------+ | MMax date No | | | Yes | | | | Compile & Save <----------------------------+ | | | <=-------------------------- Return <----------------------------------------------------+ |
以下是我抽取了某段核心部份供大家參考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // 計算輪出檔名 $ofile = md5(serialize( $src )); // 緩存是否存在,$skip_compile決定重新編譯與否 if ( $skip_compile = file_exists ( $ofile )) { // 緩存日期 $of = @ filemtime ( $lRoot . $ofile ); $infile = "" ; foreach ( $src as $f ) { // filemtime得出列表中最近更改日期 if ( $of < filemtime ( $f )) { $skip_compile = false; } // infile為輪入檔案列表,供編譯器使用 $infile .= "\"$f\" " ; } } else { $infile = "\"" . implode( "\" \"" , $src ) . "\"" ; } |
PS: 手指好冷!不想打字了,先這樣吧。

Thu Jan 16 2014 15:40:34 GMT+0000 (Coordinated Universal Time)
Last modified: Mon Oct 17 2016 07:53:02 GMT+0000 (Coordinated Universal Time)
Comments
No comments here.
Do you even comment?
website:
Not a valid website
Invalid email format
Please enter your email
*Name:
Please enter a name
Submit
抱歉,Google Recaptcha 服務被牆掉了,所以不能回覆了