即使定义了tsParticles,它仍未被识别

我正在尝试将 tsParticles 的“links”动画放入我的 Discourse 主题中。
但是,控制台显示:

theme-field-96515-common-html-script-1.js:36 Uncaught (in promise) ReferenceError: tsParticles is not defined
    at theme-field-96515-common-html-script-1.js:36:13
    at HTMLDocument.<anonymous> (theme-field-96515-common-html-script-1.js:36:13)

但您可以看到,在我的代码中,它很清楚地在顶部。
这是我的代码:

<script type="text/discourse-plugin" version="1.14.0">
  var script = document.createElement('script');
  script.src = "https://cdn.jsdelivr.net/npm/@tsparticles/preset-links@3.0.2/tsparticles.preset.links.bundle.min.js";
  document.head.appendChild(script);
  const showLinks = settings.show_tsParticles_links_animation;
  if (showLinks) {
    document.addEventListener("DOMContentLoaded", function() {
      var elements = document.querySelectorAll('section#main');
      elements.forEach(function(el) {
        var wrapper = document.createElement('div');
        wrapper.className = 'wrapper';
        el.parentNode.insertBefore(wrapper, el);
        wrapper.appendChild(el);
      });
      var elements = document.querySelectorAll('div#main-outlet-wrapper');
      elements.forEach(function(el) {
        var wrapper = document.createElement('div');
        wrapper.className = 'content';
        el.parentNode.insertBefore(wrapper, el);
        wrapper.appendChild(el);
      });
      
      (async () => {
        await tsParticles.load({
          id: "tsparticles",
          options: { preset: "links" },
          background: {
            "color": {"value":"#0d47a1"}
          }
        });
      })();
    });
  }
</script>

此外,当查看页面的 <head> 时,此标签就在那里。

看起来是一个竞态条件,tsParticles.load() 在 js 完成加载之前运行。

既然你已经在 <head> 元素中,你可以直接将创建脚本标签的代码提取出来,并将其变成一个实际的脚本标签,以便在页面加载时而不是在页面加载完成后加载 tsParticles。

如果你需要将脚本加载保留在 JS 中,你可以在 load 事件上运行代码。

const script = document.createElement('script');
script.addEventListener("load", () => {
      console.log("called", tsParticles);
      initTsParticles();
  })
script.src = "https://cdn.jsdelivr.net/npm/@tsparticles/preset-links@3.0.2/tsparticles.preset.links.bundle.min.js";
document.head.appendChild(script);

function initTsParticles() {
  tsParticles.load({
    ...
  });
}
2 个赞

太好了,非常感谢!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.