Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created August 25, 2010 20:23
Show Gist options
  • Save mjangda/550218 to your computer and use it in GitHub Desktop.
Save mjangda/550218 to your computer and use it in GitHub Desktop.
A sweet way to get around Facebook's caching of animated GIFs
<img src="" id="loading" alt="Loading..." />
<a href="#" onclick="showLoading(); return false;">Show Loading</a>
|
<a href="#" onclick="hideLoading(); return false;">Hide Loading</a>
<script>
var loadingUrl = 'http://www.example.com/images/loading-{0}.png');
var loading = loadingAnimator('loading', loadingUrl, { states: 12 });
function showLoading() {
loading.start();
}
function hideLoading() {
loading.end();
}
</script>
/**
* Cache busting loading indicator for Facebook.
* Split your indicator GIF into separate images, then use this function to animate it.
* The split frames need to be numbered accordingly.
*
* @param string id of image that holds the indicator
* @param string formatted url of the loading indicator
* - with a {0} in place of the position
* - i.e. http://example.com/images/loading-{0}.png
* @param obj options:
* - baseState: the number to start at
* - states: the number of states in the loading indicator
* - interval: time in milliseconds between switching states
* - maxTime: the max number of milliseconds to animate
*
* @return object
* {
* $loading: reference to the image
* start: function to start the loading
* end: function to end the loading
* }
*
*/
function loadingAnimator(id, imageUrl, options) {
var $loading
, interval
, running
, currentState
, currentTime
;
function init() {
$loading = document.getElementById(id);
if(!options) options = {};
options.baseState = options.baseState || 1;
options.states = options.states || 9;
options.interval = options.interval || 100;
options.maxTime = options.maxTime || -1;
}
function start() {
if(running) return;
running = true;
currentState = options.baseState;
interval = setInterval(function() {
if(options.maxTime != -1 && options.currentTime >= options.maxTime) {
return end();
}
if (currentState >= options.states)
currentState = options.baseState;
else
currentState++;
var img = imageUrl.replace('{0}', currentState);
$loading.setSrc(img);
currentTime += options.interval;
}, options.interval);
}
function end() {
clearInterval(interval);
interval = null;
running = false;
}
init();
return {
$loading: $loading
, start: start
, end: end
}
}
@camara90100
Copy link

why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment