How to force the browser to reload cached CSS/JS files?

后端 未结 30 4367
青春惊慌失措
青春惊慌失措 2020-11-21 05:49

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even be

30条回答
  •  遥遥无期
    2020-11-21 06:04

    Thanks at Kip for his perfect solution!

    I extended it to use it as an Zend_view_Helper. Because my client run his page on a virtual host I also extended it for that.

    Hope it helps someone else too.

    /**
     * Extend filepath with timestamp to force browser to
     * automatically refresh them if they are updated
     *
     * This is based on Kip's version, but now
     * also works on virtual hosts
     * @link http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files
     *
     * Usage:
     * - extend your .htaccess file with
     * # Route for My_View_Helper_AutoRefreshRewriter
     * # which extends files with there timestamp so if these
     * # are updated a automatic refresh should occur
     * # RewriteRule ^(.*)\.[^.][\d]+\.(css|js)$ $1.$2 [L]
     * - then use it in your view script like
     * $this->headLink()->appendStylesheet( $this->autoRefreshRewriter($this->cssPath . 'default.css'));
     *
     */
    class My_View_Helper_AutoRefreshRewriter extends Zend_View_Helper_Abstract {
    
        public function autoRefreshRewriter($filePath) {
    
            if (strpos($filePath, '/') !== 0) {
    
                // path has no leading '/'
                return $filePath;
            } elseif (file_exists($_SERVER['DOCUMENT_ROOT'] . $filePath)) {
    
                // file exists under normal path
                // so build path based on this
                $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $filePath);
                return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $filePath);
            } else {
    
                // fetch directory of index.php file (file from all others are included)
                // and get only the directory
                $indexFilePath = dirname(current(get_included_files()));
    
                // check if file exist relativ to index file
                if (file_exists($indexFilePath . $filePath)) {
    
                    // get timestamp based on this relativ path
                    $mtime = filemtime($indexFilePath . $filePath);
    
                    // write generated timestamp to path
                    // but use old path not the relativ one
                    return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $filePath);
                } else {
    
                    return $filePath;
                }
            }
        }
    
    }
    

    Cheers and thanks.

提交回复
热议问题