How to Set Cache for CSS/Js File

Caching specific Javascript and CSS files

You can configure IIS to cache specific files by extension. For example:

Select the folder where your css/js files reside and then click on Output Caching.
Sample Image

Then add the file extensions that you want to cache:

Sample Image

I don't think you can specify which ones to cache on a per file basis unless you write an http handler module to add the appropriate headers for each file independently, but from IIS this is how is done.

Then you can verify that you are getting 304 responses using firebug / fiddler or your tool of choice.

I hope this is helpful.

How to set cached for css and javascript

Many different ways to do this. The following is a simple example only.

CSS file called test.css (do the same for the Javascript).

body { background:#abc }

A PHP file to render the requested CSS or Javascript called t.php that includes the no cache request headers:

<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// use a switch statement for basic checking and flexibility
switch($_SERVER['PATH_INFO']) {
case '/css':
echo file_get_contents('./test.css');
exit;
case '/js':
echo file_get_contents('./test.js');
exit;
}
?>

And the header section of the HTML/PHP file

<head>                              
<link rel="stylesheet" href="t.php/css" />
<script src="t.php/js"></script>
</head>

How to let the browser cache css and js files for a https site?

Set the cache for static files either in web.config or via UI in IIS, for the static file folder you want to cache, add this in the config file and it works.

<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1000.00:00:00" />
</staticContent>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="public" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>


Related Topics



Leave a reply



Submit