我有一种 SPA,它使用 API 来获取数据。该 SPA 有一些实例,它们都使用通用样式和脚本文件。所以我的问题是,当我更改这些文件中的一行时,我将必须打开每个实例并更新文件。这对我来说真的很耗时。
一种方法是将这些文件放在服务器中的文件夹中,然后根据时间更改版本,但如果使用此解决方案,我将丢失浏览器缓存:
<link href="myserver.co/static/main.css?ver=1892471298" rel="stylesheet" />
<script src="myserver.co/static/script.js?ver=1892471298"></script>
ver 值是根据时间生成的,我无法使用浏览器缓存。我需要一个解决方案来从 API 更新这些文件,然后所有 SPA 都会更新。
在您的 head 标签中,您可以添加以下代码:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:4000/getLatestVersion"; //api path to get the latest version
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var tags = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < tags.length; i++) {
var tag = document.createElement(tags[i].tag);
if (tags[i].tag === 'link') {
tag.rel = tags[i].rel;
tag.href = tags[i].url;
} else {
tag.src = tags[i].url;
}
document.head.appendChild(tag);
}
}
};
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
</script>
您的 api 路径应允许来自处理上述代码的网站的“CORS”。
你的 api 应该返回如下所示的 json 数据:
var latestVersion = '1892471298'; //this can be stored in the database
var jsonData = [
{
tag: 'link',
rel: 'stylesheet',
url: 'http://myserver.co/static/main.css?ver=' + latestVersion
},
{
tag: 'script',
rel: '',
url: 'http://myserver.co/static/script.js?ver=' + latestVersion
}
];
//return jsonData to the client here
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)