jonathantneal / svg4everybody

Use external SVG spritemaps today
https://jonneal.dev/svg4everybody/
Other
3.29k stars 353 forks source link

API or events for completion of the completion of the ajax query #174

Open adrienrn opened 6 years ago

adrienrn commented 6 years ago

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..."

Any thoughts guys ?