初投稿します
間違いなどあればご指摘お願いします。
概要
あるWebAPIのLoading用に、画像を表示させていましたが、
プログレスバーにできないか?と依頼を受けたので実装しました。
画面の構成は、親ウィンドウと子ウィンドウでできています。
親ウィンドウから子ウィンドウを開いて、WebAPIが成功すると子ウィンドウを特定のURLに遷移させます。
この子ウィンドウでWebAPIが成功するまでの間、プログレスバーを表示したいです。
※上記の構成は珍しいと思いますが、読み替え可能だと思います。
コード
親ウィンドウ側のjs
launch.js
plugin.launchProgress = function() {
var dfd = $.Deferred();
//キャプションを設定
//sub_windowは子ウィンドウのオブジェクト
sub_window.$("#progressArea .progressCaption").text('生成中');
try {
//10秒間でプログレスバーの進捗をアニメーションします
sub_window.$("#progressbar .ui-progressbar-value").animate({width:'100%'}, 10000, 'linear');
dfd.resolve();
} catch(e) {
dfd.reject();
}
return dfd.promise();
};
plugin.startProgress = function() {
//多重実行の防止
if (!started_progress) {
started_progress = true;
plugin.launchProgress().always(function(){
started_progress = false;
});
}
};
多重実行の防止のためにDeferredを使用しています。
こちらは初めて使ってみました。
子ウィンドウ側
progress.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/progress.css"/>
<script type="text/javascript" src="/common/js/jquery.js"></script>
<script type="text/javascript" src="/common/js/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript">
$(function () {
$("#progressbar").progressbar({var:false});
$("#progressbar").progressbar("value", 0.0001); //非常に小さな値で初期化してアニメーションの準備をする
if (window.opener) window.opener.Launch.startProgress();
//0.1秒に1回キャプションを更新する
var textUpdate = function(callback) {
var percent = Math.floor($("#progressbar .ui-progressbar-value").width() / $("#progressbar").width() * 100);
$('.progressText').text(percent + '%');
setTimeout(function(){
textUpdate(callback);
},100);
};
textUpdate(textUpdate);
});
</script>
</head>
<body>
<div id="progressArea">
<div class="progressCaption"></div>
<div id="progressbar">
<div class="progressText"></div>
</div>
</div>
</body>
</html>
子ウィンドウでは表示エリアを用意して、親ウィンドウから子ウィンドウを操作しています。
CSS
progress.css
body {
background-color:lightgray;
}
# progressArea {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
text-align: center;
height: 4em;
}
# progressArea .progressCaption {
text-align: center;
height: 2em;
color: darkslategray;
}
# progressbar {
border: 1px solid #becc88;
color: #62840c;
background-color: white;
border-radius: 3px;
height: 2em;
width: 95%;
margin: auto;
}
# progressbar .progressText {
position: absolute;
top: 2.5em;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
text-align: center;
}
# progressbar .ui-widget-header {
background: #cedc98;
}
.ui-progressbar .ui-progressbar-value {
margin: 0px;
}
jquery-ui-1.10.3.custom.cssにもprogressbarの定義がありましたがこれは使用すべきかどうか謎でした。
子ウィンドウのプログレスバーは画面中央に表示します。
追記 2016-01-08
「なんちゃって」な実装とWebAPI完了の速度に差があったため、
この実装は没となりました