Wil*_*ald 23
或者在.htaccess文件中
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
Run Code Online (Sandbox Code Playgroud)
我刚刚完成了周末项目cached-webpgr.js ,它使用localStorage/web存储来缓存JavaScript文件.这种方法非常快.我的小测试显示
实现这一目标的代码很小,您可以在我的Github项目中查看它https://github.com/webpgr/cached-webpgr.js
以下是如何使用它的完整示例.
完整的图书馆:
function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};
Run Code Online (Sandbox Code Playgroud)
打电话给图书馆
requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
requireScript('examplejs', '0.0.3', 'example.js');
});
Run Code Online (Sandbox Code Playgroud)
来自PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
Run Code Online (Sandbox Code Playgroud)
适合我.
作为开发人员,您可能会很快遇到不希望缓存文件的情况,在这种情况下请参阅有关积极JavaScript缓存的帮助
在Apache .htaccess文件中:
#Create filter to match files you want to cache
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>
Run Code Online (Sandbox Code Playgroud)
我在这里也写过:
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/
| 归档时间: |
|
| 查看次数: |
139160 次 |
| 最近记录: |