Last active
December 27, 2017 03:16
-
-
Save Mosharush/7f6cf4d84aadea2d8c4d2f342673a833 to your computer and use it in GitHub Desktop.
Auto ajax function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ = jQuery; | |
var ws_ajax_manager = function(){ | |
// settings | |
this.config = { | |
content_selector: '.fl-page-content', | |
loader_src: 'https://loading.io/spinners/double-ring/lg.double-ring-spinner.gif', | |
}; | |
// Set the constructor function run on create class | |
this.const = function(){ | |
$("body ").on( "click", "a[target!='_blank']", $.proxy( this.ajax_handler, this ) ); | |
}; | |
// function will run on every page change | |
this.ajax_handler = function( e ){ | |
e.preventDefault(); | |
var $linkElm = $(e.currentTarget); | |
var targetUrl = $linkElm.prop("href"); | |
if( targetUrl.indexOf( location.origin ) !== 0 ){ | |
return true; | |
} | |
e.preventDefault(); | |
$("body").append( | |
'<style>' + | |
'#ws_loader{' + | |
' width: 100vw;' + | |
' height: 100vh;' + | |
' position: fixed;' + | |
' background: #00000080;' + | |
' text-align: center;' + | |
' top: 0; left: 0; right: 0; bottom: 0;margin:auto;' + | |
'}' + | |
'' + | |
'#ws_loader img{' + | |
' margin: 40vh auto 0;' + | |
'}' + | |
'</style>' | |
).append( "<div id='ws_loader'><img src='" + this.config.loader_src + "' alt='loading...' /></div>" ); | |
var content_selector = this.config.content_selector; | |
var jqxhr = $.ajax({ | |
method: "GET", | |
url: targetUrl, | |
async:false, | |
}) | |
.done(function( response ) { | |
history.pushState({urlPath:targetUrl},"",targetUrl); | |
var $content = $( content_selector ); | |
var newHtml; | |
newHtml = $(response).find( content_selector ).html(); | |
if( typeof newHtml == 'undefined' ) { | |
newHtml = $(response).filter(content_selector).html(); | |
} | |
console.log( newHtml, content_selector ); | |
$content.html( newHtml ); | |
}) | |
.fail(function() { | |
location.href = targetUrl; | |
}) | |
.always(function() { | |
$("#ws_loader").fadeOut( 1000, function(){ | |
$(this).remove(); | |
}); | |
}); | |
}; | |
// run the constructor | |
this.const(); | |
}; | |
ws_ajax_manager(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment