Removing PHP also meant removing the code which made the copyright year update automatically in the footer.
<?php echo date("Y"); ?>
Create an HTML element, such as a
paragraph, and add a CSS id to it.
I chose a
span tag with
Make sure that the id you choose is unique on that page.
<script> document.querySelector('#copyright-year').innerText = new Date().getFullYear(); </script>
Since there’s very little code, there’s no need to create an external file for it.
You could also use
textContent instead of
I didn’t use
innerHTML because there are no inner element tags added (e.g.
<strong></strong>). I just wanted the year in plain text.
Here’s how the final code looks like:
Copyright © <span id="copyright-year">2020</span> <script> document.querySelector('#copyright-year').innerText = new Date().getFullYear(); </script>
Why Isn’t document.write() a Good Practice?
<script> document.write(new Date().getFullYear()); </script>
But when I checked my site with Google’s PageSpeed Insights, I got this warning:
“For users on slow connections, external scripts dynamically injected via ‘document.write()’ can delay page load by tens of seconds.”
Now, it mentions external scripts injected dynamically via
document.write(), which was not the case for the above code, but I still read about it and came to the conclusion that it’s not a good option.
Here are a couple of quotes from the post on Web.dev:
Lighthouse reports any remaining calls to document.write() because it adversely affects performance no matter how it’s used, and there are better alternatives.
Remove all uses of document.write() in your code. If it’s being used to inject third-party scripts, try using asynchronous loading instead.
It clearly mentions that it affects performance no matter how it’s used, and all uses should be removed, not just injecting scripts. At least that’s how I understand it.
That’s a Wrap
I hope you found the post useful, and the code worked for you.
If you have questions or thoughts, feel free to leave a comment below.