I need to update a few hundred static HTML pages that have the copyright date hard coded in the footer. I want to replace it with some JavaScript that will automatically upd
<div>©<script>document.write(new Date().getFullYear());</script>, Company.
</div>
according to chrome audit
For users on slow connections, external scripts dynamically injected via
document.write()
can delay page load by tens of seconds.https://web.dev/no-document-write/?utm_source=lighthouse&utm_medium=devtools
so solution without errors is:
(new Date).getFullYear();
If you want to include a time frame in the future, with the current year (e.g. 2017) as the start year so that next year it’ll appear like this: “© 2017-2018, Company.”, then use the following code. It’ll automatically update each year:
© Copyright 2017<script>new Date().getFullYear()>2017&&document.write("-"+new Date().getFullYear());</script>, Company.
© Copyright 2017-2018, Company.
But if the first year has already passed, the shortest code can be written like this:
© Copyright 2010-<script>document.write(new Date().getFullYear())</script>, Company.
This is the best solution I can think of that will work with pure JavaScript. You will also be able to style the element as it can be targeted in CSS. Just add in place of the year and it will automatically be updated.
//Wait for everything to load first
window.addEventListener('load', () => {
//Wrap code in IIFE
(function() {
//If your page has an element with ID of auto-year-update the element will be populated with the current year.
var date = new Date();
if (document.querySelector("#auto-year-update") !== null) {
document.querySelector("#auto-year-update").innerText = date.getFullYear();
}
})();
});
For React.js, the following is what worked for me in the footer...
render() {
const yearNow = new Date().getFullYear();
return (
<div className="copyright">© Company 2015-{yearNow}</div>
);
}
There are many solutions to this problem as provided by above experts. Below solution can be use which will not block
the page rendering
or not even re-trigger
it.
In Pure Javascript:
window.addEventListener('load', (
function () {
document.getElementById('copyright-year').appendChild(
document.createTextNode(
new Date().getFullYear()
)
);
}
));
<div> © <span id="copyright-year"></span></div>
In jQuery:
$(document).ready(function() {
document.getElementById('copyright-year').appendChild(
document.createTextNode(
new Date().getFullYear()
)
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> © <span id="copyright-year"></span></div>