如何防止Angular 2站点上的浏览器缓存?

问题描述 投票:62回答:5

我们目前正在开发一个新项目,定期更新,我们的客户每天都会使用这些更新。该项目正在使用角度2开发,我们面临缓存问题,即我们的客户没有看到他们的机器上的最新变化。

主要是js文件的html / css文件似乎得到了正确的更新而没有给出太多麻烦。

caching angular browser-cache cache-control angular2-template
5个回答
120
投票

angular-cli通过为--output-hashing命令提供build标志来解决这个问题。用法示例:

ng build --aot --output-hashing=all

Bundling & Tree-Shaking提供了一些细节和背景。运行ng help build,记录标志:

--output-hashing=none|all|media|bundles (String) Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

虽然这仅适用于angular-cli的用户,但它的工作非常出色,不需要任何代码更改或其他工具。


31
投票

找到了一种方法,只需添加一个查询字符串来加载组件,如下所示:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

这应该强制客户端加载服务器的模板副本而不是浏览器的副本。如果您希望仅在一段时间后刷新它,则可以使用此ISOString:

new Date().toISOString() //2016-09-24T00:43:21.584Z

并对一些字符进行子字符串处理,以便它只会在一小时后更改,例如:

new Date().toISOString().substr(0,13) //2016-09-24T00

希望这可以帮助


15
投票

在每个html模板中,我只在顶部添加以下元标记:

<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">

根据我的理解,每个模板都是独立的,因此它不会继承index.html文件中的元无缓存规则设置。


1
投票

我有类似的问题,因为index.html被浏览器缓存,或者中间cdn /代理比较棘手(F5不会帮助你)。

我找了一个解决方案,100%验证客户端有最新的index.html版本,幸运的是我找到了Henrik Peinar的这个解决方案:

https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c

该解决方案还解决了客户端在浏览器中保持打开数天的情况,客户端会按时间间隔检查更新,并在较新的版本deployd时重新加载。

解决方案有点棘手,但就像一个魅力:

  • 使用ng cli -- prod生成散列文件的事实,其中一个称为main。[hash] .js
  • 创建包含该哈希的version.json文件
  • 创建一个角度服务VersionCheckService,检查version.json并在需要时重新加载。
  • 请注意,部署后运行的js脚本为您创建了version.json并替换了角度服务中的哈希,因此不需要手动工作,而是运行post-build.js

由于Henrik Peinar解决方案是针对角度4的,所以有一些细微的变化,我在这里也放置了固定的脚本:

VersionCheckService:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class VersionCheckService {
    // this will be replaced by actual hash post-build.js
    private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';

    constructor(private http: HttpClient) {}

    /**
     * Checks in every set frequency the version of frontend application
     * @param url
     * @param {number} frequency - in milliseconds, defaults to 30 minutes
     */
    public initVersionCheck(url, frequency = 1000 * 60 * 30) {
        //check for first time
        this.checkVersion(url); 

        setInterval(() => {
            this.checkVersion(url);
        }, frequency);
    }

    /**
     * Will do the call and check if the hash has changed or not
     * @param url
     */
    private checkVersion(url) {
        // timestamp these requests to invalidate caches
        this.http.get(url + '?t=' + new Date().getTime())
            .subscribe(
                (response: any) => {
                    const hash = response.hash;
                    const hashChanged = this.hasHashChanged(this.currentHash, hash);

                    // If new version, do something
                    if (hashChanged) {
                        // ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
                        // for an example: location.reload();
                        // or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
                    }
                    // store the new hash so we wouldn't trigger versionChange again
                    // only necessary in case you did not force refresh
                    this.currentHash = hash;
                },
                (err) => {
                    console.error(err, 'Could not get version');
                }
            );
    }

    /**
     * Checks if hash has changed.
     * This file has the JS hash, if it is a different one than in the version.json
     * we are dealing with version change
     * @param currentHash
     * @param newHash
     * @returns {boolean}
     */
    private hasHashChanged(currentHash, newHash) {
        if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
            return false;
        }

        return currentHash !== newHash;
    }
}

更改为主AppComponent:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    constructor(private versionCheckService: VersionCheckService) {

    }

    ngOnInit() {
        console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
        if (environment.versionCheckUrl) {
            this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
        }
    }

}

后构建脚本,使魔术,后build.js:

const path = require('path');
const fs = require('fs');
const util = require('util');

// get application version from package.json
const appVersion = require('../package.json').version;

// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);

console.log('\nRunning post-build tasks');

// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');

let mainHash = '';
let mainBundleFile = '';

// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;

// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
  .then(files => {
    mainBundleFile = files.find(f => mainBundleRegexp.test(f));

    if (mainBundleFile) {
      let matchHash = mainBundleFile.match(mainBundleRegexp);

      // if it has a hash in it's name, mark it down
      if (matchHash.length > 1 && !!matchHash[1]) {
        mainHash = matchHash[1];
      }
    }

    console.log(`Writing version and hash to ${versionFilePath}`);

    // write current version and hash into the version.json file
    const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
    return writeFile(versionFilePath, src);
  }).then(() => {
    // main bundle file not found, dev build?
    if (!mainBundleFile) {
      return;
    }

    console.log(`Replacing hash in the ${mainBundleFile}`);

    // replace hash placeholder in our main.js file so the code knows it's current hash
    const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
    return readFile(mainFilepath, 'utf8')
      .then(mainFileData => {
        const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
        return writeFile(mainFilepath, replacedFile);
      });
  }).catch(err => {
    console.log('Error with post build:', err);
  });

只需将脚本置于(新)构建文件夹中,使用node ./build/post-build.js构建dist文件夹后使用ng build --prod运行脚本


0
投票

您可以使用HTTP标头控制客户端缓存。这适用于任何Web框架。

您可以设置这些标头的指令,以便对启用和禁用缓存的方式和时间进行细粒度控制:

  • Cache-Control
  • Surrogate-Control
  • Expires
  • ETag(非常好)
  • Pragma(如果你想支持旧的浏览器)

在所有计算机系统中,良好的缓存都很好,但非常复杂。有关更多信息,请查看https://helmetjs.github.io/docs/nocache/#the-headers

© www.soinside.com 2019 - 2024. All rights reserved.