Blog

Webページに更新(再読み込み)ボタンを設置する方法

2019.09.22 コーディング

リアルタイムで利用状況を表示するシステムなどを作るときに、Webページに更新(再読み込み)ボタンがあると便利です。

Webページに更新(再読み込み)ボタンを設置する方法

HTML
<a onclick="window.location.reload(true);">
	<i class="fa fa-refresh" aria-hidden="true"></i><span>更新</span>
</a>

ここではaタグを使っていますが、もちろんinput[type=”button”]とかでも大丈夫です。

上のソースコードではFont Awesomeでリロードアイコンつけてますが、これもなくても問題ないです。

でもアイコンあった方がパッと見で分かるので親切かもですね。

参考までにCSSも一応↓

CSS
.btn_reload {
	margin-bottom: 20px;
}

.btn_reload a {
	display: block;
	width: 80%;
	max-width: 260px;
	margin: 0 auto;
	height: 36px;
	line-height: 36px;
	text-align: center;
	background: #01b264;
	color: #fff;
	text-decoration: none;
	border-radius: 5px;
	font-size: 0.875rem;
	transition: .3s ease;
}

.btn_reload a:hover {
	background: #016839;
	transition: .3s ease;
}

.btn_reload a i {
	margin-right: 0.5em;
}

Location.reload()メソッドについて

ちなみにMDNによると、

In some browsers, this method has an optional Boolean parameter, which is false by default. If true, the page is always reloaded from the server, bypassing the browser HTTP cache.

Location.reload() – Web APIs | MDN

ということで、

Location.reload()メソッドは任意でtrueまたはfalseという引数を指定でき、false(デフォルト)を指定するとブラウザキャッシュを利用して再読み込み、trueを指定するとブラウザキャッシュを回避してサーバーから再読み込み

してくれるようです。