Shortest way to print current year in a website

前端 未结 12 529
鱼传尺愫
鱼传尺愫 2020-12-07 06:45

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

12条回答
  •  庸人自扰
    2020-12-07 07:42

    You've asked for a JavaScript solution, so here's the shortest I can get it:

    
    

    That will work in all browsers I've run across.

    How I got there:

    • You can just call getFullYear directly on the newly-created Date, no need for a variable. new Date().getFullYear() may look a bit odd, but it's reliable: the new Date() part is done first, then the .getFullYear().
    • You can drop the type, because JavaScript is the default; this is even documented as part of the HTML5 specification, which is likely in this case to be writing up what browsers already do.
    • You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally despise and rail against, but in this specific use case it should be safe enough.

    It's important to note that this only works on browsers where JavaScript is enabled. Ideally, this would be better handled as an offline batch job (sed script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets. (Now I've gone and tempted fate.)


    However, unless you're using a server that can only provide static files, you're probably better off doing this on the server with a templating engine and using caching headers to allow the resulting page to be cached until the date needs to change. That way, you don't require JavaScript on the client. Using a non-defer/async script tag in the content also briefly delays the parsing and presentation of the page (for exactly this reason: because the code in the script might use document.write to output HTML).

提交回复
热议问题