Inline rendering with document.currentScript
For simple dynamic content rendering, you might not need advanced templating languages or PHP backends. The example phrase, "Come on, it’s currentYear", should render as "Come on, it’s" today. Instead of using IDs, classes, or querySelectors in your JavaScript, you can refer to the running script element directly using the document.currentScript property. The dynamic phrase "Come on, it’s" can then be written within the script as follows.
The code might seem wordy, but it can be aliased to a constant like $ via $=(...n)= document.currentScript.replaceWith(...n). This allows for a more readable and template-literal-like approach, even without explicit context.
This is the RenderJS custom element, which simply replaces itself with the result of its contents treated as JavaScript code. To use it, you must first name the tag, using an emoji (💲) as a workaround for the dollar sign ($) not being allowed in tag names. The name becomes j-💲, representing JavaScript.
When employing this technique, it's recommended to include a noscript fallback for those who don't run JavaScript. This method may seem useful only for rendering the current year, but it can be applied to various scenarios, such as displaying relative dates, generating markup per character, or creating text animations.
Unlike templating languages, you cannot perform data-driven templating using inline scripts. This is because data must be pre-injected into the global scope, and fetching data through inline scripts incurs an extra HTTP request, leading to potential performance issues. However, for personal projects, direct patching of data-driven HTML can be an effective alternative to traditional templating systems.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.