Simon Willison's Weblog

Inline rendering with document​.currentScript

8.5内容质量

TL;DR · AI 摘要

本文介绍了一种利用document.currentScript动态替换内联脚本内容的技巧,可实现页面加载时的动态渲染。

核心要点

  • 使用document.currentScript.replaceWith可实现在页面加载时动态替换脚本内容
  • 自定义函数$能简化模板语言,实现类似${}的语法糖
  • 该方法适用于需要动态生成内容的场景,如显示当前年份

结构提纲

按章节快速跳转。

  1. 介绍通过document.currentScript实现动态渲染的技巧

  2. 利用document.currentScript.replaceWith方法替换脚本内容

  3. 展示如何用<script>标签嵌入动态内容生成逻辑

  4. 通过自定义函数$实现类似模板语言的简化语法

  5. 讨论该方法在动态内容生成场景中的适用性

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • Inline Rendering with document.currentScript
    • 核心机制
      • document.currentScript.replaceWith方法
    • 实践示例
      • 年份动态替换代码
      • $函数语法糖
    • 应用场景
      • 动态内容生成

金句 / Highlights

值得收藏与分享的关键句。

#JavaScript#前端#DOM操作#动态渲染
打开原文

使用 document.currentScript 实现内联渲染

Simon Willison 的博客

通讯

#smallhead

由以下公司赞助:

Teleport

— AI 代理(及其生成的子代理)拥有与人类相同的访问权限,但它们从不睡眠。学习如何通过隔离的临时可信运行时监控和限制它们的行为。

2026年10月17日 - 链接博客

使用 document.currentScript 实现内联渲染。Lean Rada 描述了一个巧妙的技巧,利用 document.currentScript 属性。你可以使用这个特性插入一个微小的内联 <script> 元素,在页面加载时替换自身:

code
The year is <script>
document.currentScript.replaceWith(
  new Date().getFullYear())</script>

如果你定义一个快捷函数如下:

code
$=(...n)=>document.currentScript.replaceWith(...n)

你将获得一个微型模板语言:

code
The year is <script>$(new Date().getFullYear())</script>

已发布

2026年10月17日

下午9:11

最新文章

  • 欢迎Python 3.15,告别3.10,现在我可以使用3.11 - 2026年10月12日
  • 我的博客新增语音功能 - 2026年10月9日
  • Claude Haiku 5.5 - 2026年10月7日
  • 我们需要在几乎所有事物上设置默认硬预算上限 - 2026年10月3日

#primary

这是 Simon Willison 的一篇链接文章,发布于 2026年10月17日 。

javascript

768

月度简报

每月赞助10美元,获取本月最重要的LLM进展精选电子邮件摘要。

支付我以发送更少的邮件!

赞助并订阅

.metabox

#secondary

#wrapper

  • 披露信息
  • 制作信息
  • ©
  • 2002
  • 2003
  • 2004
  • 2005
  • 2006
  • 2007
  • 2008
  • 2009
  • 2010
  • 2011
  • 2012
  • 2013
  • 2014
  • 2015
  • 2016
  • 2017
  • 2018
  • 2019
  • 2020
  • 2021
  • 2022
  • 2023
  • 2024
  • 2025
  • 2026