Reputation: 10667
To enable strict mode for all JavaScript, does the "use strict"
setting need to be at the top of every imported JavaScript file, at the top of the first file, or the top of any file?
There doesn't seem to be ay documentation on this aspect.
Thanks!
Upvotes: 5
Views: 1728
Reputation: 75327
It needs to be at the top of each script that you want strict
applied to.
But, if the scripts were concatenated through minification, then "use strict" at the top of the first file would apply to all files (as they'd then be in the same file).
Because of this perceived danger (3rd party libraries?), it's advised not to do this, and instead apply it inside an IIFE for each script.
<script src="foo.js">
(function () {
"use strict";
// Your code, don't forget you've now got to make things global via `window.blah = blah`
}());
</script>
Upvotes: 11
Reputation: 17451
It goes at the top of each script, or if you only want it to apply to certain functions you can do something like:
// Non-strict code...
(function(){
"use strict";
// Your strict library goes here.
})();
// More non-strict code...
Here's a good article about it: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
Upvotes: 3