Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
adrienrn opened this issue Dec 12, 2017 · 0 comments
Open

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

adrienrn opened this issue Dec 12, 2017 · 0 comments

Comments

@adrienrn
Copy link

adrienrn commented Dec 12, 2017

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 ?

@adrienrn adrienrn changed the title API or events for completion of the Ajax API or events for completion of the completion of the ajax query Dec 12, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant