5

排错:Svelte应用的 <head> 中出现重复元素

 2 years ago
source link: https://blog.dteam.top/posts/2022-01/duplicate-elements-shown-in-head-element-of-a-svelte-app.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

打开 Svelte 应用的 html 源码,有多个重复元素(内容完全重复)存在,比如<script><style>

这种情况十有八九是因为在一个非全局的 svelte 组件中使用了 <svelte:heade>,并且这里有一个尚未关闭的 bug

了解原因之后,处理方式自然也就出来了。通常有两个选择:

  • 方法 1:将 <svelte:heade> 部分内容挪到全局组件中,比如 App.svelte
  • 方法 2:在组件的 onDestroy 方法中手工移出相关元素。

使用方法 1 时请注意

有些外部脚本可能在加载时有初始化的回调函数。比如 Google Map API,其 url 形式如下:

<script
  src="https://maps.googleapis.com/maps/api/js?key={GOOGLEMAP_KEY}&libraries=places&callback=initMap&solution_channel=..."
  async
  defer
></script>

其中,callback 指定的就是页面自定义的回调函数,在 js 加载成功之后执行。

针对于此,若采用方法 1,则可以(简单粗暴地):

  1. 在全局组件或外部首页(比如 routify 的 __app.html)

    <script src="https://maps.googleapis.com/maps/api/js?key={GOOGLEMAP_KEY}&libraries=places&solution_channel=..."></script>
    

    注意:去掉了延迟加载和 callback 参数。

  2. 在对应组件的 onMount 中调用 initMap 函数,由于此时 js 已经加载,再调用初始化函数自然可以。

当然,实际情况复杂多变,这里也只能提供解决问题的方法和思路。归根结底,只有知道了原因,办法也就呼之欲出了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK