Thursday, January 16, 2014

Javascript載入動畫的plugin

在從前當我想要在網頁中載入自己的javascript於標頭時,通常會將其包含於page load script中。然而隨著時代的轉移,我們有著AMD/CMD (異步載入)的組件了,例如:RequireJSSeaJS,CurlJS等等。因此現在我可以寫許多的JS組件並且僅在我需要它的時候將其異步載入。

在從前要在網頁內載入我們的JS時,通常我們需要某些UI控制器來指定何種資源是需要被載入的。當使用RequireJS後,此loading 時間是可以被分割到許多短暫的時間中的。 不過有時在載入JS resource 時仍然會花不少時間,也許是某些resource很大或複雜性比較高。然而理由到底為何,其實並不是很重要。最重要的是要讓用戶知道目前發生了什麼事, 故UI必須要可即時回應。

若用戶按某一個一個需要遠端載入resource的按鍵時,而RequireJS若只在resource完全載入後才回應使用者的話,當時間一久,使用者很可能會非常困惑且感到沮喪。因此,當然使用任何XHR 或遠端要求時,我也會希望如何UI 一樣的即時回應,來告知使用者目前發生了什麼事。

載入JS,當需要使用者等待時,你需要一個考慮周全的設備(device)用來顯示回應訊息於你的UI上。你可以從GitHub下載所有的程式碼,或是從下面另外一個分流的版本。

下載

使用範例

JQuery & SeaJS
<html><head>
<script src="sea.js"></script>
<script src="jquery.js"></script>
<script>
$(function(){
function fakeXHR(url, callback) {
setTimeout(function(){callback('This is some pseudo XHR content. Random number: '+Math.random());}, Math.random()*1000+500);
}
seajs.use('loading', function(loading) {
$('#btnRequest').click(function() {
var anim = loading.start($('#btnRequest'));
fakeXHR('goesNowhere.php', function(result) {
$('#txtResult').val(result);
anim.stop();
});
})
});
});
</script>
</head>
<body>
<button id="btnRequest">XHR Request</button> <br />
<textarea id="txtResult" cols="35" rows="3"></textarea>
</body></html>

Example Usage

JQuery & RequireJS
<html><head>
<script src="require.js"></script>
<script>
(function(){
require(['jquery', 'loading-jq-office-r-min'], function($, loading) {
$('#btnRequest').click(function() {
var anim = loading.start($('#btnRequest'));
fakeXHR('goesNowhere.php', function(result) {
$('#txtResult').val(result);
anim.stop();
});
})
});
function fakeXHR(url, callback) {
setTimeout(function(){callback('This is some pseudo XHR content. Random number: '+Math.random());}, Math.random()*1000+500);
}
})();
</script>
</head>
<body>
<button id="btnRequest">XHR Request</button> <br />
<textarea id="txtResult" cols="35" rows="3"></textarea>
</body>
</html>

Mootools with no module loader
<html><head>
<script src="mootools.js"></script>
<script src="loading-mt-office-x-min.js"></script>
<script>
window.addEvent('domready', function(){
$('btnRequest').addEvent('click', function() {
var anim = loading.start($('btnRequest'));
fakeXHR('goesNowhere.php', function(result) {
$('txtResult').set('text', result);
anim.stop();
});
})
function fakeXHR(url, callback) {
setTimeout(function(){callback('This is some pseudo XHR content. Random number: '+Math.random());}, Math.random()*1000+500);
}
});
</script>
</head>
<body>
<button id="btnRequest">XHR Request</button> <br />
<textarea id="txtResult" cols="35" rows="3"></textarea>
</body></html>

謝謝Hector Yeh幫我翻譯。
英文版