Skip to content

Commit

Permalink
Keeping track of ajax requests that have been made and preventing dup…
Browse files Browse the repository at this point in the history
…licates from going out
  • Loading branch information
cbaxter713 committed May 17, 2017
1 parent 88a28e1 commit 49f2b2b
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions js/inline-svg.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,42 @@

};

var selector = this.selector;
var selector = this.selector,
ajaxRequests = [];

$.extend( options, args );

//function to inline SVGs as part of the jquery plugin or part of the MutationObserver event.
var makeSVGInline = function($el){
if($el[0].nodeName === 'IMG') {
if($el[0].nodeName === 'IMG' && !$el.hasClass('loaded')) {
var svgUrl = $el.attr('src');

//If there are multiple instances of the same image, load them all with a single ajax call
var $imgInstances = $(selector).filter('[src="' + svgUrl + '"]');
//if an ajax request has not already been sent for this url
if(ajaxRequests.indexOf(svgUrl) == -1) {
//If there are multiple instances of the same image, load them all with a single ajax call
var $imgInstances = $(selector).filter('[src="' + svgUrl + '"]');

//this works better than $.ajax();
var ajax = new XMLHttpRequest();
ajax.open("GET", svgUrl, true);
ajax.send();
//this works better than $.ajax();
var ajax = new XMLHttpRequest();
ajax.open("GET", svgUrl, true);
ajax.send();
ajaxRequests.push(svgUrl);

ajax.onload = function(e) {
ajax.onload = function(e) {
//if the status is not 404 do the replacement otherwise do nothing.
if(ajax.status !== 404) {

var $svg = $(ajax.responseText);

$imgInstances.each(function() {
var $this = $(this),
classNames = $(this).attr('class');
classNames = $this.attr('class'),
$svg = $(ajax.responseText);

$svg.attr('class', classNames + ' loaded');
if (!$this.hasClass('loaded')){
$svg.attr('class', classNames + ' loaded');
$this.replaceWith($svg);
}

$this.replaceWith($svg);
$this.css('background-color', 'red');
});

}
Expand All @@ -42,14 +48,16 @@
}
}
}
};
}
};

//loop on inline SVGs loaded with the plugin
this.each(function(){
//if($this) {
makeSVGInline($(this));
//}
});
ajaxRequests = [];

$(window).load(function(){

Expand All @@ -71,6 +79,7 @@
$newInlineSVGs.each(function(){
makeSVGInline($(this));
});
ajaxRequests = [];
}
});

Expand Down

0 comments on commit 49f2b2b

Please sign in to comment.