How to fix IE 11 String.prototype.includes error in Ember?


#1

I am doing this in my controller/application.js:

  init(){
    if (!String.prototype.includes) {
      String.prototype.includes = function(search, start) {
        if (typeof start !== 'number') {
          start = 0;
        }
        if (start + search.length > this.length) {
          return false;
        } else {
          return this.indexOf(search, start) !== -1;
        }
      };
    }
  },

Even though it fixes the problem, it looks a really bad hack to me. How would you fix this properly?


#2

Are you referring to the code of the prototype function, or the place (application.init()) where you had to bolt it on to string?

If the former, I have nothing. I thought the code looked fine. If the latter, there are “initializers” that get run at bootup time. You can add to to the mix in a very clean, expected way with an app initializer called check-string-includes.js or something similar. I’d be helpful and paste a link to the place in the guides that discusses them, but am on a tiny device.


#3

Putting this into an initializer is a good idea Chris. I moved it into initializers/polyfill.js:

export function initialize(/* application */) {
  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
       // polyfill things
    };
  }
}

export default {
  name: 'polyfill',
  initialize
};

This is a cleaner approach and I can put all polyfills into one place.:grin:


#4

I prefer to prepend them to your vendor via app.import('vendor/polyfills.js', { prepend: true }). This way it’s in front of the rest of your application and vendored libs.