﻿# qUIpt：一個很有創意的 JavaScript Cache Library

[qUIpt](http://code.google.com/p/quipt/) 是一個很小很小的 JavaScript Library，所有原始碼也才只有 115 行而已（包括註解），我覺得作者 Mario Heiderich 真是太有創意了，他的原理十分簡單，使用的 Cache 方法是將資料儲存在 window 物件的 name 屬性中 ( window.name )，在這裡他是將透過 [XHR](http://en.wikipedia.org/wiki/XMLHttpRequest) ( XML Http Request ) 取回的 JavaScript 檔案內容儲存在 window.name 屬性裡。

通常 window.name 是用在 [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) 的時候指定的第二的參數，還有當我們在表單(form)中設定 target 屬性的時候，這個 target 指定的就是 window.name 的值，但預設來說 window.name 大部分來講都是空的，所以 qUIpt 就拿這個屬性來做額外的快取(Cache)用途。

qUIpt 基本的運作流程如下：

-   首先，他先檢查你的 window.name 是否有資料。
-   如果 window.name 是空的，就透過 [XHR](http://en.wikipedia.org/wiki/XMLHttpRequest) 動態下載 JavaScript 檔案，並將檔案內容儲存在 window.name 屬性中。
-   如果使用者第一次造訪你的網頁，或從其他網站進來的，就會先將 window.name 給清空，並重新下載 JS 檔回來。
-   等使用者下次造訪你的網頁（例如連到下一頁），就直接用 eval() 函示將 window.name 的 JS 讀出執行，這樣所有物件都重新被載入回來了，完全不需要重新下載 JavaScript 檔。

底下這段 code 說明了這個運作流程：

```
/**
 * some security checks to avoid arbitrary off-site
 * self.name poisoning
 */

if(document.referrer == '' || 
   document.referrer.match(/\w+:\/\/[^\/]+/)[0] 
   !== location.href.match(/\w+:\/\/[^\/]+/)[0]) {
    self.name = '';
}

/**
 * let's start
 */
if(!self.name.length) {
    quipt_load();
} else {
    quipt_eval();
}
```

原理就是這麼簡單，你可以下載看原始碼回來看，才幾行而已，也許可以激發你一些更有創意的想法。

由於此專案十分的陽春，畢竟是第一版嘛，經我個人測試之後發現只有 Firefox 能用，IE 目前是無法執行的，所以我小修了一下程式把一些僅支援 Firefox 的語法給修正了，底下的 code 應該可以運作於 Firefox 與 IE 7 ( 其他版本的 IE 我沒測試過 )。

```
/**
 * quipt - caching in the name of performance
 *
 * @author  Mario Heiderich <mario.heiderich@gmail.com> , Will 保哥 <doggy.huang@gmail.com>
 * @license LGPL
 */
(function quipt_init() {

    /**
     * the config object
     */
    var quipt_config = {
        
        /**
         * the method to call when loading is done
         *
         * hint: just set it to false if not needed
         */
        'starter' : 'my_init_function', 
        
        /**
         * add files to load to this array
         * 
         * hint: you can add as many files as you wish - as long as they 
         *       come from the same domain. quipt also supports proxied 
         *       off-domain scripts.
         */
        'files'   : [
            'jquery-1.2.6.min.js',
            'dummy-js-file-01.js', 
            'dummy-js-file-02.js'
        ],
        
        /**
         * don't touch this - private stuff! else!
         */
        'status' : 0
    }
    
    var quipt_code = [];

    /**
     * the loader method - it monitors the status of the ressource 
     * fetching and kick-starts the XHR method
     * 
     */
    var quipt_load = function() {
        quipt_request();
    }   
    
    /**
     * this method just fires XHR requests against the files given in the 
     * config literal until all ressources are fetched
     * 
     */
    var quipt_request = function() {
            try {
                console.log('loading ressources from filesystem');
            } catch(e) {}
            
            var x = new XMLHttpRequest();
            x.open('GET', quipt_config.files[quipt_config.status], true);
            x.send(null);
            x.onreadystatechange = function() {
                if(x.readyState == 4 && x.status == 200) {
                    quipt_code.push(x.responseText);
                    quipt_config.status++;
                    self.name += x.responseText + ';\n';
                    if(quipt_config.status < quipt_config.files.length) {
                        quipt_request();
                    } else {
                        quipt_eval();
                    }
                }
            }
        }   
            
        /**
         * the eval method - which is called if window.name contains 
         * the right data
         */
        var quipt_eval = function() {
            self.eval(self.name);
            if(quipt_config.starter) {
                self[quipt_config.starter]();
            }
        }
        
        /**
         * some security checks to avoid arbitrary off-site
         * self.name poisoning
         */
        if(document.referrer == '' || document.referrer.match(/\w+:\/\/[^\/]+/)[0] 
            !== location.href.match(/\w+:\/\/[^\/]+/)[0]) {
            self.name = '';
        }
        
        /**
         * let's start
         */
        if(!self.name.length) {
            quipt_load();
        } else {
            quipt_eval();
        }
    })();
```

**相關連結**

-   [qUIpt](http://code.google.com/p/quipt/) - Client side library caching with javaScript
