Home > Article > Web Front-end > js page refresh to achieve ordinary page
When I was preparing the interview questions, I encountered a page refresh, so I sorted it out and searched online. There were about eight methods. However, when I tested it, I encountered several problems. I would like to share with you:
First prepare a test page:
<!--html代码--> <h1 id="test">页面刷新</h1> <button onclick="fresh()">刷新</button
//script var h1 = document.getElementById('test'); function test(){ h1.style.color = "red"; h1.innerText = "我变化了"; } setInterval(test, 1000);
Preparation work is completed, start the page refresh method:
Five methods that can be used normally:
//第一种方法 function fresh(){ window.location.reload();//强迫浏览器刷新当前页面,默认参数为false,表示从客户端缓存里取当前页。如果指定为true,则以GET方式从服务端取最新的页面,相当于客户端点击F5。 }
//第二种方法 function fresh(){ history.go(0); }
//第三种方法 function fresh(){ location = location; }
//第四种方法 function fresh(){ location.assign(location);//assign()方法加载一个新的文档。 }
//第五种方法 function fresh(){ location.replace(location);//通过指定URL替换当前缓存在历史里(客户端)的项目,所以使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL。 }
2. Two methods that can only be executed in IE:
//第六种方法 function fresh(){ document.execCommand('Refresh');//是只有IE提供的方法,叫浏览器方法。 }
//第七种方法 function fresh(){ window.navigate(location);//只在ie可以执行,不适用于火狐等其他浏览器。 }
3. It is easy to find online, but Personally I think this is the wrong method:
//错误方法 function fresh(){ document.URL=location.href;//错误用法,document.URL只能读不能写 }
But there is also an alternative method:
//第八种方法 //window.location.href和document.location.href可以被赋值,然后跳转到其它页面 //一个窗口下只有一个window.location.href,但是可能有多个document.URL、document.location.href function fresh(){ document.location.href = location.href; //可以使用,document表示的是一个文档对象 }
//第九种方法(与第八种方法是一类) function fresh(){ window.location.href = location.href;//可以使用,window表示的是一个窗口对象 }