Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shim to redefine "const" as "var" for Internet Explorer

Internet Explorer doesn't support the "const" keyword. Can I use a shim that checks if "const" is supported and, if not, redefines it as var? I guess it would be nice if it enforced the constancy, maybe using object.Freeze, but I'd be okay with a simple shim.

UPDATE: I want this so I can use existing Javascript libraries that use "const" without modifying them. Obviously, find / replace would work, but it's messy and not very maintainable.

like image 549
Jon Galloway Avatar asked Jul 05 '11 18:07

Jon Galloway


2 Answers

You could write a server-side shim, so when the .js file is requested any const is replaced by var when the file is streamed to the browser. (Appropriate word-break / whitespace detection needed)

Since you're on the server you can't detect browser capabilities and would have to depend on the User-Agent string to do this for IE only, or have javascript that runs on the client browser tell the server that it needs non-const code.

I do a similar thing with a "userprefs.css" file that is really backed by a Java servlet, building and streaming the file specifically for each user.

like image 57
Stephen P Avatar answered Oct 08 '22 00:10

Stephen P


I would use Modernizer for this and load the appropriate script file based on support for Const. You could probably write a Grunt JS plugin that builds out the second version for IE automatically by doing a automatic find and replace for 'const'.

like image 25
Greg Benner Avatar answered Oct 07 '22 23:10

Greg Benner