Skip to content

Instantly share code, notes, and snippets.

@raultm
Created May 9, 2012 08:39
Show Gist options
  • Save raultm/2643036 to your computer and use it in GitHub Desktop.
Save raultm/2643036 to your computer and use it in GitHub Desktop.
Little jQuery plugin to prevent new load or abort previous one
(function($, window, undefined){
var requests = {}
$.fn.loadContent = function(url, opts){
/*
*
* Customization
*
*/
var defaults = {
loadingClass : 'loading',
loadingSelector : '',
stopCurrentAction : false,
}
var options = $.extend(defaults, opts || {})
/*
*
* Ways to load content
* If action is taking place
* - Don't run the new load
* - Abort the current load and launch the new
*
*/
var loadPreventingFlood = function(element, url){
if( !isLoadClassActive(element) ){
loadFunction(element, url)
}else{
console.log('Flood Prevented')
}
}
var loadStoppingActiveLoad = function(element, url){
if( requests[element] ){
requests[element].abort()
}
loadFunction(element, url)
}
/*
*
* Load with extras
*
*/
var loadFunction = function(element, url){
var $element = $(element)
setLoadClass(element)
requests[element] =
$.get(
url,
function(resp){
$element.html(resp)
unsetLoadClass(element)
}
);
}
/*
*
* Manage Loading Class
*
*/
var setLoadClass = function(element){
if(options.loadingSelector)
$(options.loadingSelector).addClass(options.loadingClass)
else
$(element).addClass(options.loadingClass)
}
var unsetLoadClass = function(element){
if(options.loadingSelector)
$(options.loadingSelector).removeClass(options.loadingClass)
else
$(element).removeClass(options.loadingClass)
}
var isLoadClassActive = function(element){
if(options.loadingSelector)
return $(options.loadingSelector).hasClass(options.loadingClass)
else
return $(element).hasClass(options.loadingClass)
}
/*
*
* jQuery Chain
*
*/
return this.each(function(index, element){
console.log(element)
if(options.stopCurrentAction)
loadStoppingActiveLoad(element, url)
else
loadPreventingFlood(element, url)
})
}
})(jQuery, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment