ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

解决浏览器缓存问题

解决浏览器缓存问题

1.index.html文件meta标签添加属性

<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" viewport-fit=cover  >

2.提前main.html处理逻辑再跳转到index.html页

<script>// 解决浏览器缓存function timestamp(url) {const getTimestamp = new Date().getTime()if (url.indexOf('?') > -1) {url = url + '×tamp=' + getTimestamp + '&loginType=' + loginType} else {url = url + '?timestamp=' + getTimestamp + '&loginType=' + loginType}return url}const getUrlParam = name => {const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')const value = window.location.search.substr(1).match(reg)if (value != null) {// 对参数值进行解码return decodeURIComponent(value[2])}return null}const loginType = getUrlParam('loginType')// console.log('main.html当前url链接地址:' + window.location.href)const url = './index.html'const newUrl = timestamp(url, loginType)window.open(newUrl, '_self')
</script>

3.动态加载文件

3.1 封装动态加载、移除文件方法
/*** 动态加载css文件* @param {*} url* @param {*} isCache*/
export function loadCSS(url, isCache = true) {let element = document.createElement('link')element.setAttribute('rel', 'stylesheet')element.setAttribute('type', 'text/css')if (isCache) {element.setAttribute('href', url + '?t=' + new Date().getTime())} else {element.setAttribute('href', url)}document.getElementsByTagName('head')[0].append(element)// document.head.appendChild(element)
}/*** 动态加载js文件* @param {*} src* @param {*} callback*   loadScript("",function(){*   console.log("加载成功")* })* var that = this; 在方法里面使用that*/
export function loadJS(jsUrl, callback, isCache = true) {const script = document.createElement('script')const head = document.headscript.type = 'text/JavaScript'if (isCache) {script.src = jsUrl + '?t=' + new Date().getTime()} else {script.src = jsUrl}if (script.addEventListener) {script.addEventListener('load', callback, false)}document.getElementsByTagName('head')[0].append(script)// head.appendChild(script)
}/*** 移除引用的JS/CSS文件* @param filename 文件名称* @param filetype 文件类型 js/css*/
export const removeFileJSandCSS = (filename, filetype) => {const targetElement = filetype === 'js' ? 'script' : filetype === 'css' ? 'link' : 'none'const targetAttr = filetype === 'js' ? 'src' : filetype === 'css' ? 'href' : 'none'const allSuspects = document.getElementsByTagName(targetElement)for (let i = allSuspects.length; i >= 0; i--) {if (allSuspects[i] &&allSuspects[i].getAttribute(targetAttr) != null &&allSuspects[i].getAttribute(targetAttr).indexOf(filename) != -1)allSuspects[i].parentNode.removeChild(allSuspects[i])}
}
3.2 页面引入
removeFileJSandCSS('nationality.js', 'js')
loadCSS('./jQuery/jquery-ui.min.css')
loadJS('./jQuery/jquery-ui.min.js', () => {})
返回列表