Kgn-web
Kgn-web

Reputation: 7565

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.

Upvotes: 6

Views: 10060

Answers (2)

Mr Lister
Mr Lister

Reputation: 46619

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

Upvotes: 3

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23873

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.)

Upvotes: 6

Related Questions