LoginSignup
0
0

More than 3 years have passed since last update.

【Nuxt】headに記述したJavaScriptが2回実行されてハマった話【SPA】

Posted at

症状

nuxt.config.jsに下記の設定をする

nuxt.config.js
    mode: 'spa',
    head: {
        script: [
            {
                innerHTML: `(function(){console.log('HelloWorld!')}());`
            }],
        __dangerouslyDisableSanitizers: ['script'],
    },

起動してみる
image.png

なぜかHelloWorld!が2回出力される。

2回呼ばれる原因

  1. ビルドされたhtmlに記載されてるScriptタグが読み込まれる(1回目の出力)
  2. Scriptタグの比較を行われる
    「htmlに記載されてるScriptタグ」と「nuxt.config.jsに定義されているScriptタグ」 で比較され、差異があった場合にScriptタグが再配置される。
    この時に「nuxt.config.jsに定義されているScriptタグ」がフォーマットが書けられた状態の内容で比較される為、差分があったと見なされ、タグが再配置される
htmlに記載されてるScriptタグ
(function(){console.log('HelloWorld!')}());
比較に使用されるフォーマットされたScriptタグ
(function (){console.log('HelloWorld!')}());
  1. 再配置されたScriptタグが読み込まれる。(2回目の出力)

対策

再配置されたScriptタグの内容をコピーし、nuxt.config.jsの内容を置き換える

nuxt.config.js
    mode: 'spa',
    head: {
        script: [
            {
                innerHTML: `(function(){console.log('HelloWorld!')}());`
            }],
        __dangerouslyDisableSanitizers: ['script'],
    },
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0