How to provide ECMAScript 5 (ES 5)-shim? - javascript

ECMAScript Fifth Edition (released December 2009) introduces a bunch of new methods (see this table for details). However, there still are older browsers out there which do not implement those new methods.
Luckily, there exists a convenient script (written in JavaScript) - ES5-shim - which implements those methods manually in environments where they don't exist.
However, I am not sure how to provide ES5-shim... Should I just "give" it to all browsers, like so:
<script src="es5-shim.js"></scipt>
Or should I include a check in order to only "bother" those browsers which really need it, like so:
<script>
if ( !Function.prototype.hasOwnProperty( 'bind' ) ) {
(function () {
var shim = document.createElement( 'script' );
shim.src = 'es5-shim.js';
var script = document.getElementsByTagName( 'script' )[0];
script.parentNode.insertBefore( shim, script );
}());
}
</script>
(I'm using Function.prototype.bind to check if a browser implements all new ECMAScript 5 methods. According to the compatibility table which I linked above, bind is the "last bastion" when it comes to implementing ECMAScript 5 methods.)
Of course, for this shim to be effective, it has to be executed before all other scripts, which means that we want to include the above mentioned SCRIPT elements early in the page (in the HEAD, before all other SCRIPT elements).
So, would this second example be a good way to provide ECMAScript 5-shim to browsers? Is there a better way to do it?

ES5-Shim will only shim parts that the browsers don't implement, so just give it to all browsers. It'll handle the detection of what needs to be shimmed and what doesn't.
But pay attention to the caveats listed on what shims don't work correctly in some instances. I've had issues with that in the past and it causes a ton of pain until you realize the answer was super simple...

This seems to work for me:
<!--[if lt IE 9]><script src="java/es5-shim.min.js"></script><![endif]-->

At present, the solution that works best with ES5-Shim is to use the library in all environments and allow it to detect which features it needs to patch at run-time. It would be even better to deliver it from a community CDN to maximize cross-site cache hits.
That being said, there is an open opportunity to create systems that combines feature detection, agent fingerprinting, and dynamic bundling to automatically generate and deliver targeted shim subsets. The scope of the problem extends far beyond just ES5-Shim and could be applied to all sorts of shims.

Related

How to detect if browser is compatible with ES2015 [duplicate]

This question already has answers here:
Javascript ES6 cross-browser detection
(10 answers)
Closed 7 years ago.
I have a big chunk of JS libraries that I should rewrite since it's really old and outdated. So, I decided to come up with a solution where I would just use most of ES2015 features like rest parameters.
The thing is, I am sure all the clients would not have their browser up-to-date and I am confused whether I will face any issue regarding their browser is compatible with my new JS libs.
So, I was wondering if I could detect whether the client browsers are compatible with ES2015. And if not, I would just include my old JS library.
I am looking for a solution like Conditional comments, but I am getting nowhere to solution.
Any help in HTML, JS or PHP is appreciated. Please kindly suggest your advice.
I was wondering if I could detect whether the client browsers are
compatible with ES2015. And if not, I would just include my old JS
library.
You cannot do that, simply because AFAIK there's no browser that fully supports ES2015. Also, you don't really want to maintain two different versions of your code, because it's painful and it could get messy really quick.
The approach nowadays is to use a transpiler, which is sort of a compiler that compiles your ES2015 code to ES5 (the JavaScript that every browser knows). It is still kind of messy, but at least you get to write only one version of your code, and it's ES2015.
I think Babel (formerly 6to5) is the most popular transpiler. You can check out their website for getting started.
As to answer your actual question,
How to detect if browser is compatible with ES2015
You can do that in many ways. I'm not sure what could be the most reliable one, but for example you could simply try on your browser's console:
'Promise' in window
If this statement returns true, then the current browser supports promises, which is a new feature of ES2015, so you could assume that it supports most of the features of ES2015.
This is not enough for most cases though; you may want to be 100% sure that what you're using is not going to throw a SyntaxError in any old browser.
A solution could be to manually check for each feature you want to use. For example, if you need the Fetch API, you could create a function that tells you if the current browser supports it:
function isFetchAPISupported() {
return 'fetch' in window;
}
You can do this for any new API you need. However, if you need something syntactically different, I think your only bet is eval() (as Katana314 suggested). For example, in order to check support for rest parameters you could do:
function isRestSupported() {
try {
eval('function foo(bar, ...rest) { return 1; };');
} catch (error) {
return false;
}
return true;
}
This works great in Firefox, because the rest parameters are supported.
It works as well on Safari, returning false because rest parameters are not supported there yet.

Why does passing a javascript variable with the same name as a div Id pass the div

I think this is absolutely ludicrous.
Given
HTML
<div id = "statCounter"></div>
Javascript
var statCounter = 5;
Executing
console.log(statCounter);
// logs <div id = "statCounter"></div>
How can this be? How absurd is this?!!?
http://jsfiddle.net/rkkj58nw/
This was a feature implemented in IE (presumably as a syntax sugar to avoid peppering your code with getElementById() in the long ago days before frameworks, I'm talking 1999).
Originally, other browsers such as Netscape didn't have this misfeature. But at some point some non-IE browsers started to implement this feature to be compatible with corporate websites that uses IE specific features.
I'm not entirely sure but I believe by now this is specified in some standard (either ECMAScript or HTML5 or something else). So now all browsers implement this "feature".

extjs4 Object doesn't support property or method 'indexOf' IE 8 workaround issue

My User defined sort function does not work in IE 8.
Object doesn't support property or method 'indexOf'
roles_store.sort([{
sorterFn: function(v1, v2) {
var order = ['read-only', 'user', 'admin', 'super'],
v1o = order.indexOf(v1.get('role_name')),
v2o = order.indexOf(v2.get('role_name'));
return v1o < v2o ? -1 : 1;;
}
}]);
The following link shows a workaround:
How to fix Array indexOf() in JavaScript for Internet Explorer browsers
I tried replacing indexof with Array.prototype.indexOf
v2o = order.Array.prototype.indexOf (v2.get('role_name'));
I apologize if I missed something here
IE 8 is a little old and it includes an old javascript version. It doesn´t have a lot of very useful methods that we use everyday. I recommend to include the tiny Array prototype extensions library (link). That library allows you to use all the methods (for arrays) that all new browsers (with newer javascript version) include.
You also can use the Extjs methods as Evan suggests (they work well) but you have to have that in mind all the time and most of the snippets and code samples that you find in internet or this site won´t run (you will have to translate them to use extjs methods). Another problem is that your code will works ok in Chrome and FF but not in IE if you not take care.
It is much more easy and safe to include the extensions that I recommend you, that´s what we did in our own project and it was a great solution.
Use Ext.Array.indexOf, it defers to the native indexOf where possible.
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Array-method-indexOf

Writing ECMAScript5 compliant code

I want to build a library in JavaScript/JScript/ECMAScript...whatever you want to call it, which will target modern standards (HTML5, CSS3, ESv5) with that in mind, any browser that supports the standard! Now I know there are already plenty of useful libraries out there, i.e. jQuery and MooTools. Of course they're great and I already use those where necessary, but I should not be forced to jump on the same bandwagon as every other developer just because it's popular!
So for the sake of the following questions, let us not concern ourselves with 3rd party libraries such as jQuery and MooTools. Lets get down to nitty-gritty JavaScript/JScript/ECMAScript.
Firstly, I asked a question prior to this (What's the difference between JavaScript, JScript & ECMAScript?), as I did not know what the difference was.
Thankfully I concluded the following:
ECMAScript is the language specification. JavaScript and JScript are dialects of ECMAScript.
JavaScript is Mozilla's implementation of ECMAScript.
JScript is Microsoft's implementation of ECMAScript.
OK, that was a nice simple answer wasn't it? But here's some questions which stem from that:
is "JavaScript" supported in non-mozilla browsers, and to what extent?
is "JScript" supported in non-microsoft browsers, and to what extent?
Based on those two questions, I did a little digging and ran a simple test on IE9, FF14 and GC19.
Here is the test code:
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Template</title>
<script language="JavaScript1.3">
jsver = "1.3";
</script>
<script language="JavaScript1.4">
jsver = "1.4";
</script>
<script language="JavaScript1.5">
jsver = "1.5";
</script>
<script language="JavaScript1.6">
jsver = "1.6";
</script>
<script language="JavaScript1.7">
jsver = "1.7";
</script>
<script language="JavaScript1.8">
jsver = "1.8";
</script>
<script type="text/javascript">
document.write("<B>Your browser supports JavaScript version " + jsver + ".</B>")
</script>
</head>
<body>
</body>
</html>
The results were: IE9 = JSv1.3, FF14 = JSv1.8, GC19 = JSv1.7
OK, then I ran this test, which tests for ECMAScript version 5 support:
http://kangax.github.com/es5-compat-table/#showold
Again using the same browsers (IE9, FF14, GC19), ESv5 seems to be fairly well supported!
Now comes the tricky bit! I come from a Microsoft background, and write software using languages like C#, ASP.NET etc, so naturally, my IDE of choice is Visual Studio (currently 2010). When I look through the JavaScript intellisense I see things like ActiveXObject, Array, Object, etc.
Should I trust VS2010's intellisense?
Where can I find a reference of ESv5 supported objects and features?
How do I detect if a browser supports a particular object or feature?
Is there anything better than VS2010 out there that will help me write compliant ESv5 code?
Is it safe to override implementations of existing objects like Object, Number, Boolean etc, or should I just extend the existing implementation?
Finally, concerning myself with jQuery. Let's say I can't be bothered to write the core compliancy & functionality myself, can I just write my library to sit on top of jQuery...or is this just a copout?
1) Nope. Certainly it won’t restrict to just valid ECMAScript.
2) http://kangax.github.com/es5-compat-table/ is always useful.
3) You can just check to see if it’s defined. E.g.
typeof(Array.isArray) === 'function'; // true in newer browsers, false in IE8
4) Your best bet is to read the spec! Using "use strict"; in your code will also catch some classes of errors and it good practise. More explanation on strict mode at http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
5) Certainly I wouldn’t replace the original objects. If you’re going to extend properties I’d first double-check that a compliant implementation doesn’t already exist. E.g. PrototypeJS added (before browsers implemented it) a document.getElementsByClassName. When browsers started implementing it natively they found out that sites using Prototype were still using the slow JS-based version. The fix was just to wrap Prototype’s definition in a if (document.getElementsByClassName == undefined) { }
2) I find the Overview you provided pretty good. What else do you want?
3) A good library to even out the differences between the browser is ES5-shim. It autodetects the features and provides shims for the browsers who lack support.
4) Always use "use strict"; and a have good editor of your choice which has some kind of code-highlighting and perhaps code-completion. I use the browser consoles or firefox scratchpad (silly name for a good tool) for quick hacking sessions and put it all together in notepad++ (= the IDE of your choice).
5) Augmenting the native javascript objects has been debated a lot and has pros and cons. Prototype and MooTools go this way. jQuery takes the other way and provides a separate object for that. I personally prefer to leave the native (and especially host) objects alone and have your own namespace with the functions you need.

disable javascript on ie browsers

is there a way to disable a certain script for all ie browsers?
You can make use of conditional compilation to determine if the client is using MSIE.
var IE = /*#cc_on!#*/false;
which can be used as
if (IE) {
// IE.
} else {
// Others.
}
Only in IE, the ! will be compiled and taken in the expression, resulting in a new expression !false, which is logically true. This works better than $.browser.msie because it can be fooled by the useragent and also better than document.all because it would affect certain Opera versions as well.
That said, what is it you're trying to disable? You can on the other hand also make use of feature detection. Here's a discussion about this: Browser detection versus feature detection
I wouldn't recommend this, but:
if(!$.browser.msie) {
//non IE script
}
I would fix the script to work in IE, or exclude it based on some feature the browser doesn't support...not just because it's IE. With any browser a feature could be added via an update tomorrow, and your script would still exclude it. See $.support for more on feature detection.
Excluding something from running because "it isn't supported" is a perfectly valid scenario. However, excluding something because "IE doesn't support it...when I wrote this code" isn't a good approach. Instead, check if the feature that you need is present, and the user gets the richest experience possible in their current browser.
You could not include the javascript at all for IE browsers using Microsoft's recommended way of inserting a conditional comment:
<!--[if !IE]>
<script src="myscript.js" type="text/javascript"></script>
<![endif]-->
or simply wrap the code you want to exclude in the comment.
If you're speaking of IE 6, you can crash it by calling this function :
function crash_IE6() {for(x in document.open);}
Seriously, the most use way of deteting IE is checking the presence of document.all... but it still isn't a good thing.
You should nerver check what browser your script is running on... you should just check the presence of the needed methods.

Categories

Resources