0

I have an app up and running, and it works great in Chrome and Firefox. Safari is another story. For the sake of example, let's pretend this is my app:

'use strict';

const x = 3;

function test(){
  let y = 4;
  return y;
};

When I run it in Safari I get:

SyntaxError: Unexpected keyword 'const'. Const declarations are not supported in strict mode.

Then if I remove 'use strict' I get:

SyntaxError: Unexpected identifier 'y'

At this point I decided to take my first look into transpiling, so I installed Babel and I have my client-side code converted to ES5 and sitting in a new folder.

My question now is, what's the best practice for loading the original code if a user is using Chrome/Firefox, but loading the transpiled code if they're using Safari? Is my head even in the right place here?

  • Possible duplicate of [Safari/Babel/Webpack Const declarations are not supported in strict mode](http://stackoverflow.com/questions/33878586/safari-babel-webpack-const-declarations-are-not-supported-in-strict-mode) – omarjmh Mar 30 '16 at 18:38
  • Just load the transpiled code in all browser –  Mar 30 '16 at 18:38
  • You also have to worry about IE –  Mar 30 '16 at 18:39
  • @Omarjmh While the error that anthonator was encountering was the same as mine, his question was in regards to why Babel wasn't changing his const declarations to var. My question is in regards to the best way to load scripts after they've been successfully transpiled. – Daniel Emery Mar 30 '16 at 22:47
  • @user104317 In my particular case it seems like yours might be the most straightforward and simple solution. Is that common practice? To write in ES6, transpile to ES5, and just serve the ES5 code? – Daniel Emery Mar 31 '16 at 01:42
  • Yes, most people just serve ES5. Keeping track of which browsers support which features is a pain. –  Mar 31 '16 at 11:04

2 Answers2

0

To detect if safari is being used:

var safariCheck=Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;

Then you can load the code you want for safari if the above statement qualifies. If it does not you can load the Firefox or Chrome code.

0

The cleanest way to check feature is to use Modernizer

With this library you can check that browser have es6 feature ready with this code:

 if (Modernizr.es6array) {
    loadNewCode();
  } else {
    loadOldCode();
  }

You can find more examples and documentation here.

Ygalbel
  • 5,214
  • 1
  • 24
  • 32