Zubayer
Zubayer

Reputation: 581

How to load multiple items in ajax?

I'm trying to call different external SVG in a single HTML page. If I stick to one, everything works perfectly. As soon as I want to call different SVG sprites, I end up with only one loading. So basically, it loads only one sprite and ignores others. Am I missing something in the syntax here?

I'm using the following ajax code //I'm a newbie, so I'm sure that I'm making a terrible mistake here :)

<script>
var ajax = new XMLHttpRequest();
ajax.open("GET", "sprite1", "sprite2", "sprite3", true);
ajax.send();
ajax.onload = function(e) {
var div = document.createElement("div");
div.innerHtml = ajax.responseText;
document.body.insertBefore(div, document.body.childNodes[0]);
}
</script>

Then in HTML I am using this

<svg class="sprite1">
    <use xlink:href="#icon-name">
</svg>

Upvotes: 0

Views: 80

Answers (1)

sbgib
sbgib

Reputation: 5828

The XMLHttpRequest.open() method can only accept one URL, so you need a separate request for each sprite. Try like this:

var sprites = ["sprite1", "sprite2", "sprite3"];

sprites.foreach(function(sprite, index) {
   var ajax = new XMLHttpRequest();
   ajax.open("GET", sprite, true);
   ajax.send();
   ajax.onload = function(e) {
      var div = document.createElement("div");
      div.innerHtml = ajax.responseText;
      document.body.insertBefore(div, document.body.childNodes[0]);
   };
});

Be aware that the order in which the sprites are returned cannot be guaranteed, so you may wish to load each one to a specific element in the HTML. You can use the index in the example to determine which has been loaded.

Upvotes: 1

Related Questions