工具可以动态加载js、css等界面资源,解决各种客户端静态资源缓存不刷新问题。如果有顺序要求,即可在传值的时候保证顺序即可。
loadResource.js
let pattern = new RegExp(/\.css/, 'ig');
function recursionLoad(urls, flatIndex) {
if (urls.length == flatIndex.index) {
return;
}
let url = urls[flatIndex.index];
flatIndex.index++;
if (pattern.test(url)) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.style = 'text/css';
link.href = url + '?t=' + new Date().getTime();
document.body.appendChild(link);
link.onload = function() {
recursionLoad(urls, flatIndex);
}
} else {
const script = document.createElement('script');
script.src = url + '?t=' + new Date().getTime();
script.async = false;
document.body.appendChild(script);
script.onload = function() {
recursionLoad(urls, flatIndex);
}
}
}
function loadScriptWithTimestamp(urls, callback) {
let flatIndex = {
index: 0
};
recursionLoad(urls, flatIndex);
let interval = setInterval(() => {
if (flatIndex.index == urls.length) {
callback();
clearInterval(interval);
}
}, 500);
}
先在需要刷新资源的界面引入工具
<script src="loadResource.js"></script>
然后调用loadScriptWithTimestamp函数
<script>
loadScriptWithTimestamp(urls, function(){
//这里放入需要等待资源加载完成后的js逻辑
})
</script>