Skip to content

Instantly share code, notes, and snippets.

@hinell hinell/loadImages.js
Created Jul 12, 2019

Embed
What would you like to do?
/**!
* Description : A few snipets that help to load bunch of images or svgs using DOMParse API
* Author : <hinell@github.com>
* Last-Modified: July 13, 2019
* License : Copyright (c) 2019 Alexander Davronov
* In case of disclosure of use of this piece of software you may face prosection
* if any of the following conditions are met:
* 1. You failed to make a due mention of the aforementioned author
* 2. You failed to copy this license text next to this piece of software
*
* Otherwise anyone is free to use this piece of software at their own risk and responsibility.
* No warranty or any form of safety guarantees are provided.
*/
/**
* Loads image sources into specified target
* @param {object} args
* @param {string=} args.basePath
* @param {string[]} args.images
* @param {HTMLElement} args.target
*/
let loadSvgs = async function ({ basePath, images, target }) {
if (!basePath) basePath = "";
if (!(images && target)) {
throw new Error(`Invalid argument`)
}
let domparser = new DOMParser();
let svgPromises = images.map(async function (src, i, images) {
let response = await fetch(basePath + src);
let text = await response.text();
let xmlDoc = domparser.parseFromString(text, "image/svg+xml");
return xmlDoc.firstElementChild
})
let svgImages
try {
svgImages = await Promise.all(svgPromises)
svgImages.forEach(function (svgDoc, i, array) {
target.append(svgDoc)
})
} catch (e) {
console.log(e)
}
};
/**
* Loads image sources into specified target
* @param {object} args
* @param {string=} args.basePath
* @param {string[]} args.images
* @param {HTMLElement} args.target
*/
let loadImages = async function ({ basePath, images, target }) {
if (!basePath) basePath = "";
if (!(images && target)) {
throw new Error(`Invalid argument`)
}
let htmlElements = images.map((src, i, images) => {
let el = new Image();
el.src = basePath + src;
return el
});
htmlElements.forEach(function (el, i, htmlElements) {
target.append(el)
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.