Explain Codes LogoExplain Codes Logo

Code not running in IE 11, works fine in Chrome

javascript
polyfills
compatibility
debugging
Nikita BarsukovbyNikita Barsukov·Nov 25, 2024
TLDR

To make your code functional in IE 11, you need to address missing features and transpile JavaScript to ES5 with Babel:

  1. Babel Setup: Run npm install @babel/core @babel/cli @babel/preset-env
  2. Config: In .babelrc, add { "presets": ["@babel/preset-env"] }.
  3. Compile: Run npx babel src.js -o src-compiled.js.

Replace ES6/js and CSS features with versions that IE 11 supports, and ensure the doctype is <!DOCTYPE html> to avoid entering quirks mode.

ES6 Features and IE 11 Compatibility

The startsWith ES6 feature isn't supported by IE 11. However, we can tackle this situation by employing a polyfill:

// Oh no! 'startsWith' is missing? Let's fix it. if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; // "indexOf" to the rescue! return this.indexOf(searchString, position) === position; }; }

Alternatively to check if a String starts with a particular substring, you can use indexOf:

var str = "Hello world!"; if (str.indexOf("Hello") === 0) { // Bingo! String starts with "Hello" }

Remember the position parameter should be set to 0 to check from the start of the string.

For Angular 2+ projects, include core-js/es6/string for a polyfilled startsWith method along with other ES6 features.

For users who love external libraries, try Lodash and its _.startsWith method:

// Nothing can come between Lodash and compatibility! _.startsWith('abc', 'a'); // returns true

Differences in supported JavaScript features often explain why code behaves differently across browsers. The JavaScript engine and the standard adopted play crucial roles.

When debugging for IE 11, it's pivotal not to forget that it doesn't support many ES6 features. Here are few quick antidotes:

  1. Check your feature against compatibility tables available at "Can I Use".
  2. Keep off from unsupported ES6 features or implement relevant polyfills.
  3. Relate to the trusted, tested, and tried methods like indexOf.
  4. Libraries like Lodash comes handy when ensuring consistent behavior across browsers.

Debugging in IE 11 Using Other Approaches

At times, the developer tools could appear unresponsive or insufficient. As an alternative, you could use console-based debugging with console.log or console.dir.

In situations where you need more visual snapshot, use conditional comments specific to IE or layout-specific custom CSS following the selectors: <!--[if IE]>.

Remember, IE 11 might lack full-fledged support for Flexbox or CSS Grid. Have backup plans like floats or display: table-cell ready for tricky layout situations for IE 11.