E
E
Egor Telnov2021-12-20 12:14:22
HTML
Egor Telnov, 2021-12-20 12:14:22

How to disable browser caching of the index page?

There is an app in React. I ran into a problem that the browser caches the page if it is bookmarked. Those. a new release rolls out, but users see the old styles and scripts until they refresh the page. It will be updated (without resetting the cache). After that, the latest versions of the files are downloaded.

In this regard, the question is - how can I disable this caching?

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

If you insert this code into index.html, will the scripts with styles be cached, or will the browser load them every time?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Smirnov, 2021-12-23
@sasha-hohloma

You need to add hash to filenames. When the content changes, the hash next to the script/style file name will change, and after the new release, users will see updates without resetting the cache. It is undesirable to completely disable the cache, because. then regular users will need to upload files every time and wait for the download to finish each time.
To implement this approach, you need to configure Webpack, for more details, you can look in the documentation or in the example below for Webpack 5 from one of the working projects:

const path = require('path');
const htmlPlugin = require('html-webpack-plugin');

const publicPath = path.join(__dirname, 'build');

module.exports = {
    entry: './source/index.tsx',
    output: {
        path: publicPath,
        filename: '[name].[contenthash].js',
        chunkFilename: '[name].[chunkhash].js',
        publicPath: '/',
    },
    devServer: {
        static: publicPath,
        historyApiFallback: true,
        hot: true,
        port: 6790,
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx', 'ttf'],
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                include: path.resolve(__dirname, 'source'),
                loader: 'ts-loader',
                options: {
                    transpileOnly: true,
                },
            },
        ]
    },
    plugins: [
        new htmlPlugin({
            publicPath: '/',
            template: './source/index.html',
            favicon: './source/assets/images/favicon.png'
        }),
    ],
};

V
Vladimir Korotenko, 2021-12-20
@firedragon

make the root location cache-free, in nginx it is cached by default.
https://stackoverflow.com/questions/41631399/disab...

S
sasmoney, 2021-12-20
@sasmoney

.load as a last resort on every page load

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question