I don’t think it’s a good idea to leave
statements in production code, it’s a good idea to prevent your site from breaking if you accidentally do. I include this condition in the first script that loads on the page of most of my projects
if (typeof console == "undefined") {
window.console = {
log: function () {}
};
} |
This JavaScript simply defines an empty function if the console is not available in the browser so stray log statements don’t break production for your valuable customers.
In a recent project I wanted to be able to dynamically set a production flag in JavaScript. Doing so would allow me to keep my production analytics free from dev and staging environment events. Because my dev and staging environments don’t run on a .com domain extension I was able to go with this simple script
var de = document.location.hostname.split('.');
de = de[de.length - 1];
window.prod = (de == 'com') ? true : false; |
Then when I need code to only respond when in production it’s as easy as
if(window.prod) {
// do awesomeness
} |
Splitting up the domain in JavaScript to set the production flag has been working well and I’m quite happy with it so far. If you have suggestions or want to share what you have done, please share in the comments below.