💬 观点Simon Willison
Inline rendering with document.currentScript — 用 document.currentScript 让内联脚本原地替换自身,实现极
用 document.currentScript 让内联脚本原地替换自身,实现极简模板渲染
2026-10-17原文
本文为要点摘要,完整细节以原文为准。
- Lean Rada 发现
document.currentScript可让内联<script>在页面加载时用replaceWith()把自身替换成任意节点,例如直接输出当前年份。对 agent 与工具链的含义:生成 HTML 片段时可用这种自替换脚本做零依赖的动态占位符。 - 把
replaceWith封装成$=(...n)=>document.currentScript.replaceWith(...n)后,<script>$(new Date().getFullYear())</script>就成了一种极小的模板语法。对开发者的含义:无需引入模板引擎即可在静态页面里插入少量动态值。 - 该技巧完全基于浏览器原生 API,文章只给出这一种用法示例,没有讨论性能、安全或兼容性细节。对工具链的含义:适合轻量场景,但采用前需自行评估 CSP 等约束。
原文:Inline rendering with document.currentScript · 作者 Simon Willison