tsParticles が定義されていないのに、定義されている

Discourse テーマに tsParticles の「links」アニメーションを適用しようとしています。
しかし、コンソールに次のようなエラーが表示されます。

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() が JavaScript の読み込み完了前に実行されている競合状態のようです。

すでに <head> 要素内にいるので、tsParticles 用のスクリプトタグを作成するコードを抽出し、実際のスクリプトタグにして、ページ読み込み後にではなくページと一緒に読み込まれるようにすることができます。

スクリプトの読み込みを JavaScript 内に保持する必要がある場合は、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.