API or events for completion of the completion of the ajax query
adrienrn opened this issue · comments
adrienrn commented
What I needed was to trigger some things when the icons were loaded, eg. making a skeleton layout like facebook or slack.
const svg4everybody = require('svg4everybody');
const modernizr = require('modernizr');
let xhrOnOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
// fires on every readystatechange ever
// use `this` to determine which XHR object fired the change event.
if (this.responseURL && '.svg' === this.responseURL.slice(-4)) {
if ('function' !== typeof Event) {
if ('function' !== document.createEvent) {
// IE8 => not supported for now.
return;
}
// Fallback case for IE, not supporting new Event.
var event = document.createEvent('Event');
event.initEvent('done.svg4everybody', true, true);
return document.dispatchEvent(event);
}
event = new Event('done.svg4everybody');
document.body.dispatchEvent(event);
}
}
XMLHttpRequest.prototype.open = function() {
if (modernizr.eventlistener) {
this.addEventListener('load', onStateChange);
} else if ('function' === typeof window.attachEvent) {
// Fallback case for IE, not supporting addEventListener.
this.attachEvent('load', onStateChange);
}
xhrOnOpen.apply(this, arguments);
}
It's vanilla javascript and taking only IE9+ into account. Could have done better, I'll improve it when I'll be able to do extended test on IE8.
It's not a very elegant way to do it and I'd love to find a way to implement it inside svg4everybody. What I don't know is, "Would it be better to..."
- make the xhr object available from the outside (public) ? Meh.
- add some public API to add / remove listener to the xhr object ?
- work with events as I've "done" here ?
Any thoughts guys ?