Website performance is a hot topic these days.
Not only do visitors to your website expect it to load at lightning speed, but the biggest search engine of them all—no prize for guessing, Google—uses page speed as a ranking factor in its search results.
So if your website loads too slowly, visitors will drop out and it won’t reach its full ranking potential on Google. I guess that’s why you found yourself wondering: “If I leave comments in my HTML code, will it slow down the loading of my website?”
That’s a good question. On the one hand, leaving comments in your code makes it easier to build on and debug. And HTML markup is no exception. On the other, you might want to reconsider doing so if it affects performance.
So… does it?
Leaving comments in your website’s HTML markup slows loading because web browsers have more code to parse. This results in slower selection of DOM elements with CSS and slower DOM manipulation with JavaScript.
The real question to ask here is, by how much?
Though this is something that only you can benchmark as your website’s developer, the following rule of thumb applies:
A couple of dozen lines of comments in an HTML document consisting of a few thousand lines of code probably won’t do much. But a heavily-commented HTML document requested by a large number of users every day can do plenty.
When in doubt, leave HTML comments on your local machine and/or in your development environment—but remove them from the staging and production versions of your site.
(I added staging here on purpose because it should be as close a copy of the production version as possible).
Removing HTML Comments Isn’t Enough
It should go without saying that removing comments from your HTML documents needs to be just one part of a broader speed optimization strategy for your website. It won’t do much by itself.
At the very least, you should make sure that your HTML markup and CSS style sheets are minified in production to remove all redundant characters from the perspective of browser painting.
Where possible, substitute CSS3 rules for JavaScript DOM manipulations and consider extracting the critical CSS (that is, the CSS code for the part of the page that’s above the fold) and inlining or embedding it into your HTML document to reduce the time it takes to reach the Largest Contentful Paint (LCP).
All media files should be optimized for reduced size and/or saved in modern formats, like .webp for images and .webm for audio and video files (with appropriate fallback for legacy browsers). Depending on the use case for your website, consider using a Content Delivery Network (CDN).