Html как отключить кеш

Disable cache for some images

I generate some images using a PHP lib. Sometimes the browser does not load the new generated file. How can I disable cache just for images created dynamically by me? Note: I have to use same name for the created images over time.

13 Answers 13

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

The random number generation can happen either on the server when serving the page (just make sure the page itself isn’t cached. ), or on the client (using JavaScript).

You will need to verify whether your web-server can cope with this trick.

Instead of random numbers, use the timestamp that the data changed or a version number of the reflected data.

Please note: You do not actually prevent the browser from caching the image, you only prevent looking at the cached image. Applying proper headers to your image is the best way imho (see the solution of lhunath below). Since this way you also fill the cache unnecessarily with images you do not want to cache with the cost of causing less cache space for things you actually do want to be cached.

Читайте также:  Java this inside method

this does not really works, the image needs to be flushed another way (usually on image cropping, the image remains the same)

Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you’ll need several headers to get the desired effect on a range of browsers.

header ("Pragma-directive: no-cache"); header ("Cache-directive: no-cache"); header ("Cache-control: no-cache"); header ("Pragma: no-cache"); header ("Expires: 0"); 

this will applay to the whole page. I can’t disable cache for one image only(a specific image from that page)?

@Thorpe: It applies to HTTP responses. What is contained in the response is irrelevant. Whether it’s image data, HTML data or whatever else. If it didn’t work, you probably didn’t do it right. Check the HTTP headers on your response to see if they have been correctly assigned.

I wish this worked. Chrome doesn’t have any problems, but Firefox 14 and IE 8 refuse to refresh the images even with the above headers being sent. This would have been so much cleaner solution than adding some arbitrary parameters to the query string. sigh

@PawelKrakowiak Note that adding headers won’t work for images that are already cached, since the browser doesn’t even ask the server about them and therefore will never see the headers. They will work for any image requests made after you added them.

This solution is intended for programmers, not web designers. I thought I would point that out because one cannot just open and image and add headers to an image, unless they themselves are generating the image in a programming language and this seems to be confusing commenters.

Solution 1 is not great. It does work, but adding hacky random or timestamped query strings to the end of your image files will make the browser re-download and cache every version of every image, every time a page is loaded, regardless of whether or not the image has changed on the server.

Solution 2 is useless. Adding nocache headers to an image file is not only very difficult to implement, but it’s completely impractical because it requires you to predict when it will be needed in advance, the first time you load any image that you think might change at some point in the future.

Enter Etags.

The absolute best way I’ve found to solve this is to use ETAGS inside a .htaccess file in your images directory. The following tells Apache to send a unique hash to the browser in the image file headers. This hash only ever changes when the image file is modified and this change triggers the browser to reload the image the next time it is requested.

If you need to do it dynamically in the browser using javascript, here is an example.

var d = new Date(); document.getElementById(«graph»).src = «http://www.kitco.com/images/live/gold.gif?ver mt24″>

)» data-controller=»se-share-sheet» data-se-share-sheet-title=»Share a link to this answer» data-se-share-sheet-subtitle=»» data-se-share-sheet-post-type=»answer» data-se-share-sheet-social=»facebook twitter devto» data-se-share-sheet-location=»2″ data-se-share-sheet-license-url=»https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f» data-se-share-sheet-license-name=»CC BY-SA 3.0″ data-s-popover-placement=»bottom-start»>Share
answered May 24, 2011 at 21:03
Add a comment |
15

I checked all the answers and the best one seemed to be (which isn’t):

However, if you add cache=none parameter (which is static «none» word), it doesn’t effect anything, browser still loads from cache.

Solution to this problem was:

where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.

However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.

To solve this problem, I needed to hash $_GET but since it is array here is the solution:

$chart_hash = md5(implode('-', $_GET)); echo ""; 

Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:

echo ""; 

filemtime() gets file modification time.

Источник

How to prevent html5 page from caching?

I converted a plain vanilla HTML page to HMTL5/CSS3 with a responsive layout, and for security reasons (dictated by the security people) the page must never cache. The page previously used and to prevent the page from being cached. What replaces this in HTML5? How do you prevent an html page from caching in the client? I’ve spent a week reading about manifest files, but they seem to do exactly opposite of what I want as attaching a manifest file explicitly causes the page it is attached to to cache. And please don’t refer me back to the w3c definition of which meta elements are now allowed — I understand that HTML5 does not include the cache-control or Pragma in meta elements. I need to know what it does include that will prevent a page from being cached.

4 Answers 4

In the beginning of code you need to use this:

Then create manifest.appcache with such content:

CACHE MANIFEST # Cache manifest version 1.0 # no cache NETWORK: *

Thanks, that work to prevent the file from caching, but now it pops up a info bar in Firefox stating: «This web site is asking to store data on your computer for offline use.» Which again is exactly the opposite of what I want to happen. Very annoying and will not be too user friendly for our novice users — we cater to healthcare professionals who are less than Internet savvy. Anyway to keep the manifest and ditch the info bar or is this just the way it is with firefox?

an equivalent solution is to reference a manifest file that doesn’t exist: but this will show up in the console in chrome developer tools.

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. developer.mozilla.org/en-US/docs/Web/HTML/…

I dislike appcache a tremendous amount. It almost works well but can be a real unforgiving pain. While doing some code refactoring, I realized that after logout, i could browse back to the the last page. Of course, refreshing browser it would force user back to login but this is not desired.

After searching around and seeing the options, I started to get a bit frustrated. I do not want to use appcache. I then realized that my code was redirecting to login page after destroying the session and got an idea, what if, I redirect to the home page instead? And voila, page was loaded, session checked (and of course not there), user redirected to login. Problem solved.

I have been struggling with the same issue for quite some time. What works for me — at least so far — in Chrome, FF and IE is doing the following:

1) reference the manifest file From what I understand, this will cache everything that follows in this HTML document, hence a manifest file is needed to prevent this from happening:

2) use a manifest file filename.appcache with the following content which basically says: for all files, do not read from cache but from network server:

CACHE MANIFEST # 2015-09-25 time 20:33 UTC v 1.01 NETWORK: * 

3) a third step is required: each time you upload a (partial) update of your website, also change the manifest file by changing the date and time stamp in the comment(#) line. Why? Because if you do not change the manifest file, it will not be read and it will default to step 1 and thus cache and read from cache. The fact that the manifest file is changed, however, enforces the manifest file to be read again, and thus enforces that the «do not read from cache but read from network server» instruction therein, is applied again.

The previous answer may not consistently work to prevent caching or to clear existing cache in chrome but there is a work around.

1) To clear existing cache in chrome, it may be necessary to update all files of the website (eg by linking to a new css file on every page) along with an update of the cache-manifest before existing cache in chrome gets cleared upon the second visit of a page (because of the «flow» of the way in which a page is rendered: the first time a page is visited, the browser reads and caches the manifest , while proceeding with loading from existing cache. Only upon the second visit will the newly stored updated manifest be read and applied).

2) and if none of that helps, it is possible to include a script in the manifest file itself to check for a new manifest and if found, reload it and use the new manifest. This did the trick and resolved all remaining cases I tested for where files had remained persistently cached in chrome. I found this script on this page by Jason Stimpel.

  

Источник

Как отключить кэш раз и навсегда на странице

Что нужно прописать на странице, чтобы все браузеры, которые заходят на эту страницу, без исключения никогда не обращались в кэш, а каждый раз заново перечитывали стили и скрипты из присоединённых файлов, т.к. там постоянно бывают изменения. Следующие предписания абсолютно не дают никакого результата:

И не дадут. Это указания кеширования самой страницы, а не включаемых файлов. Для включаемых файлов надо отдельно отдавать заголовок Cache-control, например средствами web сервера. Или делать динамические url для самих включаемых файлов, вроде