How to use 'let' (and supported ECMAScript 6 features) in both Firefox and Chrome
The naïve solution, assuming you have control over the script itself, is to set some global within the script and check if it exists later. Iff it doesn't, replace this script element with one without the special MIME type so it can run on other browsers. The global can safely be ignored after that.
<script type="application/javascript;version=1.7"> 'use strict'; window.fx = true; let foo = 'bar'; console.log(foo);</script><script> if (typeof window.fx === 'undefined') { var oldScript = document.querySelector('script[type="application/javascript;version=1.7"]'); var text = oldScript.text; document.body.removeChild(oldScript); var newScript = document.createElement('script'); newScript.text = text; document.body.appendChild(newScript); }</script>
The main disadvantage here is the extra HTTP request that may be incurred when referencing an external script, especially if the script is not cached. Since Firefox is the only browser on which you can guarantee that the script will never be requested more than once per page load, this has the potential of being incredibly wasteful on other browsers.
As an alternative, you can use feature detection as mentioned in the comments to insert the script
element either with or without the type
attribute rather than including it in the HTML source to start with. According to MDN's compatibility table, basic support is available starting from Firefox 2.0 (in JavaScript 1.7), so you can pick pretty much any Firefox-specific feature from whichever version you wish to extend your support to.
var script = document.createElement('script');script.text = '"use strict"; let foo = "bar"; console.log(foo);';try { document.querySelector('::-moz-selection'); script.type = 'application/javascript;version=1.7';} catch (e) { // Not Firefox, leave MIME type unchanged}document.body.appendChild(script);