I have various polyfills/shims I would like to use in my AngularJS app.
For example, classList
is not supported in IE9 and below.
I've tried two ways of defining polyfills in my app:
First, by simply placing all polyfills at the top of my app.js
page, wherein all other modules are defined and configured.
Second, I've tried this:
angular.module('polyfills',[]);
angular.module('polyfills')
.config([function() {
// all polyfills in here
}]);
Both options work. However, both options seem a little weird to me. Intuitively, using .config
feels like I should be sticking to configuring things like providers, interceptors, etc. It seems like this might be an issue that has already been resolved in the past, and I have the feeling some sort of best practice has come about as a result.
Is there a better way of doing this?
Don't put your polyfills in an angular module, that's weird and not what you want. What you want is for the js implementation in each browser to look the same, so load your polyfills before any other js resource. Create a js file (or more if you want each polyfill in its own file) that contains your polyfill(s) and is loaded in a script tag before any of your other js files. Your polyfills should also be inside IIFE's.
Here's what an example polyfill for Array.from (this is a very simple polyfill for demo purposes):
array-from-polyfill.js
(function() {
'use strict';
Object.defineProperty(Array, 'from', {
configurable: false,
enumerable: false,
value: function (object) {
'use strict';
return [].slice.call(object);
}
});
})();
Then put the following tag in your index.html (or whatever you call your top level template) before any other js files. Yes, even before angular or bootstrap resources.
<script src="path/to/array-from-polyfill.js"></script>
Two last items of note. First, always use Object.defineProperty, and set 'enumerable' to false. That is unless you want certain ways of iterating over an object's properties to pick up your polyfills. This means that you'll have to fiddle with MDN's polyfills, but that's fine. You should probably know your way around defineProperty anyways.
Second, I suggest that you load your polyfills in every browser, even if the browser already has that function. Basically, your executed code should be the same everywhere, as much as possible. Nothing is more irritating that having a bug in one specific browser, because it is (or is not as the case may be) using your polyfill. This isn't a universal truth, so do what feels right to you.
Don't forget to make sure that your polyfills are also loaded in your testing environment, and to regularly check if you can retire a polyfill.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句