dataqbs

Inline rendering with document​.currentScript

· Source: Simon Willison

Lean Rada has released a short note that shows how to use the document.currentScript property to create inline code snippets that automatically replace themselves when a page loads. The technique involves inserting a tiny <script> element whose sole purpose is to call document.currentScript.replaceWith() with the content you want to display. In the example, the script inserts the current year using new Date().getFullYear(), so the text “The year is” is completed dynamically without any external code or post‑load DOM manipulation.

To make the syntax even simpler, the author defines a shorthand function $ that accepts any number of arguments and passes them to replaceWith(). With this helper, the same operation becomes <script>$(new Date().getFullYear())</script>, creating a miniature template language that lets you embed calculated values directly in the HTML.

This approach is useful for developers who want to reduce external JavaScript and keep content‑generation logic close to the markup. Because it runs at load time, it eliminates the need for additional events or later DOM tweaks, which can improve both efficiency and code clarity. In an environment where rendering speed and front‑end simplicity are increasingly critical, having a lightweight way to inject dynamic data straight into the HTML offers a practical advantage for web projects of any size.

Read the original article on Simon Willison

This summary is an informational synthesis produced by dataqbs.com. All rights to the original content belong to its author and the cited media outlet. We act solely as curators of technology news and claim no authorship.

Read this in Español · Deutsch