Reputation: 1701
I'm trying to plot points on an SVG image from data from an API response, but when a large number of points has to be plotted, app crashes. How can the DOM manipulation be done asyncronously without crashing the app? This is the function executing:
export const plotPoint = function (path) {
var ns = 'http://www.w3.org/2000/svg';
var x, y = 1;
path.map(function (value, index) {
var coordinates = value.split(',');
x = parseInt(coordinates[0], 10);
y = parseInt(coordinates[1], 10);
var startCircle = document.createElementNS(ns, 'circle');
startCircle.setAttributeNS(null, 'cx', x);
startCircle.setAttributeNS(null, 'cy', y);
startCircle.setAttributeNS(null, 'r', 1);
startCircle.setAttributeNS(null, 'fill', 'green');
document.querySelector("#map").append(startCircle);
});
}
Upvotes: 0
Views: 38
Reputation: 141829
You don't need to do anything asynchronously. Just avoid modifying the DOM until you're done making all your circles and then insert them all into the DOM at once:
export const plotPoint = function (path) {
var ns = 'http://www.w3.org/2000/svg';
var x, y = 1;
var docfrag = document.createDocumentFragment();
path.map(function (value, index) {
var coordinates = value.split(',');
x = parseInt(coordinates[0], 10);
y = parseInt(coordinates[1], 10);
var startCircle = document.createElementNS(ns, 'circle');
startCircle.setAttributeNS(null, 'cx', x);
startCircle.setAttributeNS(null, 'cy', y);
startCircle.setAttributeNS(null, 'r', 1);
startCircle.setAttributeNS(null, 'fill', 'green');
docfrag.appendChild(startCircle);
});
document.querySelector("#map").appendChild(docfrag);
}
Upvotes: 1