hash css and js files to break cache. Is it slow?

你。 提交于 2019-11-28 06:03:25

问题


I have some script that generates templates of a page. Also, this scripts renders <script> and <link rel='stylesheet'> tags in the HTML.

I'd like to add cache-breaking feature with "?v=xxxxx" parameter.

I do it in such a way:

foreach ($scripts as &$script) {

    // get script file name
    $script = "{$this->_js_folder}/{$script}";

    // get it's realpath
    $realfile = realpath(substr($script,1));

    // hashing the file
    $hash = md5_file($realfile);

    // adding cache-breaking number
    $script .= '?v='.$hash;

} //: foreach

Isn't it slow, to hash about a dozen files every time user refreshes the page?


回答1:


That's cruel to your users to break the cache every time. How often do you change those files?

At any rate, I would suggest using a timestamp-- far faster than md5.




回答2:


Personally, I wouldn't hash the file, that's a waste of resources. Instead of it, i would add the last-modified timestamp into the v?=.... I mean something like this:

foreach ($scripts as &$script) {

    // get script file name
    $script = "{$this->_js_folder}/{$script}";

    // get it's realpath
    $realfile = realpath(substr($script,1));

    // getting last modified timestamp
    $timestamp = filemtime($realfile);

    // adding cache-breaking number
    $script .= '?v='.$timestamp;

} //: foreach



回答3:


Depending on how you update your site, you should probably use the date modified instead.

However, if you always re-upload every file, this is not a good idea.
However, you should then be able to cache the hash in memory (and perhaps also check the timestamp)



来源:https://stackoverflow.com/questions/6460967/hash-css-and-js-files-to-break-cache-is-it-slow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!