Reputation: 63
Knowing that Snap.load();
is asynchronous, I'm looking for a way to append the loaded files in the requested order. This is the code I'm using:
s = Snap(800, 800);
function loadSvg(url) {
Snap.load(url, appendSvg);
};
function appendSvg(svg) {
g = svg.select("g");
s.append(g);
};
loadSvg('https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/b.svg');
loadSvg('https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/a.svg');
I found this (http://svg.dabbles.info/snaptut-loadmulti.html), but I wonder if there's any simpler, official Snap.svg, way to do it? For me it feels that the Snap.load();
should have a feature for this included?
Upvotes: 2
Views: 2133
Reputation: 15841
You can sequence asynchronous tasks nicely with Javascript promises (polyfill for platforms that do not yet have native Promise), e.g.:
// Helper to convert Snap.load() into a Promise.
function loadSVG(url) {
return new Promise(function(resolve, reject) {
Snap.load(url, resolve);
});
};
// Make an array of Promises.
var loadPromises = [
loadSVG('http://example.com/a.svg'),
loadSVG('http://example.com/b.svg'),
loadSVG('http://example.com/c.svg'),
...
];
// Wait for all the Promises to finish.
Promise.all(loadPromises).then(function(results) {
// results contains the loaded SVGs, in order.
for (var i = 0; i < results.length; ++i) {
var svg = results[i];
// Your processing of each SVG goes here.
var g = svg.select("g");
s.append(g);
}
});
Upvotes: 6