Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the version of Javascript in HTML

As the new JavaScript ES6 is launched. I am trying to know how do I specify the version.

Suppose, if I want to use HTML5, I declare at the top of the html page

<!DOCTYPE HTML> 

Similarly, if I think to use jQuery then I do use jQuery 2.1.4 or any I do it the src pointing to below url

https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js

This is how we write js in html.

<script type="text/javascript"> 
 //js
</script>

or

<script type="text/javascript" src="external.js"> </script>

How do I specify that version ES6 should be used for the script, in case it is not supported by browser, fall back to ES5.

like image 402
Kgn-web Avatar asked May 14 '16 07:05

Kgn-web


2 Answers

As others have said: The browser will use whatever JavaScript engine it has built in ... be that 3, 5 or some version of 6.

While there used to be a way to specify a version of JavaScript using the lang parameter, that has been obsolete for at least 10 years, and only mattered for JavaScript versions 1 and 2, which behaved quite differently.

If you need to make sure that your code runs on an older JavaScript engine, you must use a transpiler, such as Babel. The resultant code will run on ES3, ES5 or 6.

Your other options are:

  • Write ES6 code and where it runs, it runs. Where it doesn't -- oh well.
  • Write ES5 code and run it everywhere. (Well, everywhere modern.)
like image 187
Jeremy J Starcher Avatar answered Sep 18 '22 10:09

Jeremy J Starcher


One way to use different versions of your script is to load them depending on what features are present. Say, the hypot function in the Math library.
For instance with jQuery:

if (typeof Math.hypot == "undefined")  // Is hypot defined?
   $.getScript('old_routines.js');     // No, load old library
else
   $.getScript('new_routines.js');     // Yes, assume ES6 and load new library
like image 34
Mr Lister Avatar answered Sep 20 '22 10:09

Mr Lister