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

夙愿已清 提交于 2019-12-03 06:30:32

问题


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?


回答1:


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




回答2:


This seems to work for me:

<!--[if lt IE 9]><script src="java/es5-shim.min.js"></script><![endif]-->



回答3:


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.



来源:https://stackoverflow.com/questions/8732846/how-to-provide-ecmascript-5-es-5-shim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!