|
Post by account_disabled on Jan 6, 2024 0:52:27 GMT -5
这可能需要一段时间。您可以事先使用 XHR 下载脚本,但浏览器将拒绝重用它,因为下载的资源类型与现在尝试使用该资源的类型不同。 所以,你可以做什么? 在预加载之前,不多。(在某些情况下,您可以访问eval()脚本的内容,但这并不总是可行,也没有副作用。)但是通过预加载,您可以!复制 您可以在页面加载过程的早期运行该脚本,即在您希望脚本执行之前运行(但是一旦您相当有信心脚本加载不会干扰其他需要加载的更重要的资源)。然后,当您希望它运行时,您只需注入一个script标签即可。 复制 主体:120+ 原生 React UI 组件与 Next.js 完全兼容 尝试 KENDOREACT 基于标记的异步加载器 另一个很酷的技巧是使用onload处理程序来创建某种。 基于标记的异步加载器。Scott Jehl是第一个对此进行实验的人,作为他的 loadCSS 库的一部分。简而言之,您可以执行以下操作: <复制 并在标记中获取异步加载的样式!斯科特还为该功能提供了一个很好的演示页面。 这同样适用于异步脚本。 你说 Whatsapp 号码列表 我们已经有了<script async>?嗯,<script async>很好,但是它阻止了窗口的 onload 事件。在某些情况下,这正是您想要的,但在其他情况下则不然。 假设您想要下载分析脚本。您希望它下载得相当快(以避免失去分析脚本未捕获的访问者),但您不希望它延迟任何影响用户体验的指标,特别是,您不希望它延迟负载。(您可以声称加载不是影响用户的唯一指标,您是对的,但早点停止旋转加载图标仍然很好)。 通过预加载,实现这一点很容易: 复制 (包含长 JS 函数。 作为属性可能不是一个好主意onload,因此您可能希望将该部分定义为内联函数。) 响应式加载 由于preload 是一个 link,根据规范它有一个media属性。(Chrome 目前不支持,但很快就会支持。)该属性可以启用资源的条件加载。 那有什么用呢?假设您网站的初始视口具有适用于该网站的桌面/宽视口版本的大型交互式地图,但仅显示移动/窄视口版本的静态地图。 如果您很聪明,您只想加载这些资源之一而不是两者。唯一的方法是使用 JS 动态加载它们。但这样做会使这些资源对预加载器不可见,并且它们的加载时间可能会晚于必要时间,这可能会影响用户的视觉体验,并对SpeedIndex分数产生负面影响。 我们可以做什么来确保浏览器尽早意识到这些资源? 你猜到了!预载。 我们可以使用 preload 来提。
|
|