Ionic 2,Chrome仍从磁盘缓存加载

4

我正在开发一个移动应用程序,并使用以下命令构建并运行适用于浏览器的版本(引入所有必要的钩子,ionic serve不包含这些)

ionic build browser --desktop --testing && http-server platforms/browser/www/

昨天和前几周都很完美,我停止并启动同样的命令,它构建/编译所有内容,一切都很好。然后我更新了谷歌浏览器。现在,无论我做什么,Chrome都会从磁盘缓存中拉取所有这些资源,即使我删除并重新创建它们也是如此。有什么想法可以解决吗?我不想每次重新加载时都清除缓存,而且似乎这会在以后引起其他问题。我不知道为什么或如何更改,我的Ionic2应用程序中没有任何项目或配置设置不同。使用cmd-shift-R而不是仅使用cmd-R重新加载似乎可以强制Chrome不从磁盘缓存中加载,但我感到困惑,想要理解发生了什么...
1个回答

2

Chrome会缓存很多东西,但是你可以通过使用缓存破坏来强制它从服务器加载资源而不是从缓存中获取资源:

加载模板:

var timestamp = (new Date()).getTime();

$ionicPopup.show({
    scope: $scope,
    title: 'Work!',
    templateUrl: '/templates/roll-timer-popup.html?update='+timestamp
});

加载脚本/样式表:

<script src="myscripts.js?update=123..."></script>

<link rel="stylesheet" type="text/css" href="theme.css?update=123...">

对于脚本/样式表,您可以动态创建它们并插入时间戳。

或者当您的脚本文件被捆绑在一起时,您可以使用一个脚本将时间戳写入最终的index.html文件以便部署,使用nodejs脚本编写此脚本,我曾为我的一个项目编写过此脚本:

const fs = require('fs');

var filename = process.argv[2];

var regExp = /[.|\w]+[.]js/;
var contentToAttach = ['<!-- CONTENT ATTACHED BY '+process.argv[1]+' -->','you can put other content in here that is put into at the end of your file'];

fs.readFile(filename, {
    flag : 'r',
    encoding: 'utf-8'
},(err, oldFileContent) => {
    if (err) throw err;
    var fileContent = oldFileContent;
    var oldScriptName;
    var now = (new Date()).getTime();
    var lastIndexPos = 0;
    while (oldScriptName = oldFileContent.match(regExp)) {
        var newScriptName = oldScriptName + '?update=' + now;
        var newIndexPos = fileContent.indexOf(oldScriptName);
        if (newIndexPos !== lastIndexPos) {
            fileContent = fileContent.replace(oldScriptName, newScriptName);
            lastIndexPos = newIndexPos;
        }
        else {
            // same filename found
            var fildContentSlice = fileContent.slice(newIndexPos+oldScriptName.length);
            fildContentSlice = fildContentSlice.replace(oldScriptName, newScriptName);
            fileContent = fileContent.slice(0,newIndexPos+oldScriptName.length)+fildContentSlice;
        }
        oldFileContent = oldFileContent.replace(oldScriptName, '');
    }
    var wholeContent = fileContent+'\n\r'+contentToAttach.join('\n\r');
    fs.writeFile(filename,wholeContent, (err) => {
        if (err) throw err;
        console.log('File: '+filename+' is updated!');
    });
});

它会在文件中找到的每个脚本标签中插入?update=123...。 要在shell中执行此脚本,请输入:

node updateScript.js path_to_your_html_file

希望这有所帮助。

1
谢谢,但这并不是我面临的确切问题。Ionic2将所有内容捆绑成漂亮的包,这些包恰好具有相同的名称,Chrome决定通过缓存来提供帮助。所以,这就是一切。对于已部署的应用程序来说,它会很好,并且我提到的ctrl+shift+R重新加载也足够好...我只是想了解发生了什么,因为我的项目中没有任何更改,只是更新了最新版本的Chrome :-\ 非常烦人。 - Joshua Ohana
不用谢。抱歉我不知道 Chrome 是如何实现的,但我已经更新了我的答案,以帮助你处理捆绑的脚本文件。希望能对你有所帮助。 - Blauharley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接