tiptap/examples/helpers/svg-sprite-loader.js

81 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-08-21 05:02:21 +08:00
;(function(window, document) {
2018-11-09 05:03:10 +08:00
'use strict';
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
var isSvg = document.createElementNS && document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' ).createSVGRect;
var localStorage = 'localStorage' in window && window['localStorage'] !== null ? window.localStorage : false;
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
function svgSpriteInjector(source, opts) {
var file;
opts = opts || {};
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
if (source instanceof Node) {
file = source.getAttribute('data-svg-sprite');
opts.revision = source.getAttribute('data-svg-sprite-revision') || opts.revision;
} else if (typeof source === 'string') {
file = source;
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
if (isSvg) {
if (file) {
injector(file, opts);
} else {
console.error('svg-sprite-injector: undefined sprite filename!');
}
} else {
console.error('svg-sprite-injector require ie9 or greater!');
}
};
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
function injector(filepath, opts) {
var name = 'injectedSVGSprite' + filepath,
revision = opts.revision,
request;
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
// localStorage cache
if (revision !== undefined && localStorage && localStorage[name + 'Rev'] == revision) {
return injectOnLoad(localStorage[name]);
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
// Async load
request = new XMLHttpRequest();
request.open('GET', filepath, true);
request.onreadystatechange = function (e) {
var data;
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
if (request.readyState === 4 && request.status >= 200 && request.status < 400) {
injectOnLoad(data = request.responseText);
if (revision !== undefined && localStorage) {
localStorage[name] = data;
localStorage[name + 'Rev'] = revision;
}
}
};
request.send();
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
function injectOnLoad(data) {
if (data) {
if (document.body) {
injectData(data);
} else {
document.addEventListener('DOMContentLoaded', injectData.bind(null, data));
}
}
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
function injectData(data) {
var body = document.body;
body.insertAdjacentHTML('afterbegin', data);
if (body.firstChild.tagName === 'svg') {
body.firstChild.style.display = 'none';
}
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
if (typeof exports === 'object') {
module.exports = svgSpriteInjector;
} else {
window.svgSpriteInjector = svgSpriteInjector;
}
2018-08-21 05:02:21 +08:00
2018-11-09 05:03:10 +08:00
} (window, document));