Skip to content

Commit

Permalink
Fixing mutiple bad requests for images.
Browse files Browse the repository at this point in the history
It was requesting all elements that had the selector multiple times. Now it checks once per mutation.addedNodes and only fires on image elements.
  • Loading branch information
jermartin77 authored Mar 3, 2017
1 parent 8e75406 commit 301ed10
Showing 1 changed file with 35 additions and 23 deletions.
58 changes: 35 additions & 23 deletions js/inline-svg.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,19 @@

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

//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();

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

var $svg = $(ajax.responseText);

Expand All @@ -33,7 +34,8 @@
$el.addClass('not-loaded');
}
}
};
}
};

//loop on inline SVGs loaded with the plugin
this.each(function(){
Expand All @@ -42,24 +44,34 @@
//}
});

//observe the DOM for mutations, if anything changes on the page scan it for new img selector
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
$(window).load(function(){

var nodesAdded = false;
//observe the DOM for mutations, if anything changes on the page scan it for new img selector
var observer = new MutationObserver(function(mutations) {

if (mutation.type === 'childList' && mutation.addedNodes.length) {
var $inlineSVGs = $("img" + selector).not('.loaded');

$inlineSVGs.each(function(){
makeSVGInline($(this));
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length) {
nodesAdded = true;
} else {
nodesAdded = false;
}
});
if(nodesAdded) {
var $newInlineSVGs = $(selector).not('.loaded');

$newInlineSVGs.each(function(){
makeSVGInline($(this));
});
}
});
});
});

observer.observe(document.body, {
attributes: true,
childList: true,
subtree: true
observer.observe(document.body, {
attributes: true,
childList: true,
subtree: true
});
});
};
}( jQuery ));
Expand Down

0 comments on commit 301ed10

Please sign in to comment.