[javascript] 処理中のLoadingを表示して、処理完了時に非表示にする方法
何かの処理を行っているときには、処理中のLoadingを表示して、処理完了時に非表示にする方法は以下の通り
目次
ローディングのGifをダウンロードして、サーバにアップロードする
下記WEBページで簡単にLoading gifを作成することができる。
gifをサーバにアップロードしておくこと
Loader Generator – Ajax loader
Javascriptの実装
ページどこかに下記Javascriptを実装する
<script>
/* ------------------------------
Loading イメージ表示関数
引数: msg 画面に表示する文言
------------------------------ */
function dispLoading(msg){
// 引数なし(メッセージなし)を許容
if( msg == undefined ){
msg = "";
}
// 画面表示メッセージ
var dispMsg = "<div class='loadingMsg'>" + msg + "</div>";
// ローディング画像が表示されていない場合のみ出力
if($("#loading").length == 0){
$("body").append("<div id='loading'>" + dispMsg + "</div>");
}
}
/* ------------------------------
Loading イメージ削除関数
------------------------------ */
function removeLoading(){
$("#loading").remove();
}
</script>
使い方例:S3にファイルをアップロードして、完了したらLoadingを非表示にする
s3_client().putObject({Key: filename, ContentType: file.type, Body: file, ACL: "public-read"},
function(err, data){
// if failed, alert
if(data !== null){
alert("アップロード成功!");
} else {
alert("アップロード失敗.");
}
removeLoading();
});
};
CSSの実装
<style>
#loading {
display: table;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: #fff;
opacity: 0.8;
}
#loading .loadingMsg {
display: table-cell;
text-align: center;
vertical-align: middle;
padding-top: 140px;
background: url("[LoadingイメージのURL]") center center no-repeat;
}
</style>