Avoiding stale CSS and JS files

Problem:

When I modify the static css or js file under webroot/css or webroot/js and then release a new version of my web-application, browsers do not detect the change, so users see a broken page (because of stale css or js).

Solution

I implement a custom version of AssetManager and put it in the components/AssetManager.php:


<?php


class AssetManager extends CAssetManager {


	protected function hash($path)

	{

		return sprintf('%x',crc32($path.'-'.Yii::getVersion().'-'.Yii::app()->params['version']));

	}


}

?>



Then I add the following in the main configuration file:




    // application components

    'components' => array(

        'assetManager' => array(

            'class' => 'AssetManager',

        ),

    ),

    // application-level parameters that can be accessed

    // using Yii::app()->params['paramName']

    'params' => array(

        // this is used in contact page

        'version' => '1.0',

    ),




Now when I release a new version of the App I can change the Yii::app()->params[‘version’] and all of the assets will be republished under different paths.

Question

May be there is a better way to solve this issue? How do you solve it?

I’m using publish for each file separately. This way Yii detects changes and re-publishes it.

there is also another solution - you can use modified CClientScript which attach version to every CSS/JS URL as a get param. When you change version - browsers will fetch the file again.

I did an extension providing this functionality: http://www.yiiframework.com/extension/csclientscript/

Hi, redguy!

Thanks for sharing your solution.

I think this issue is so common, that it would worth mentioning somewhere on the wiki or in documentation.

Even if Yii republishes the file, the URL wouldn’t change and browsers would still use the cached version of the CSS/JS file.