【问题标题】:Nuxt + External script -> Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded externalNuxt + 外部脚本-> 无法在“文档”上执行“写入”:无法从异步加载的外部写入文档
【发布时间】:2021-04-25 01:07:40
【问题描述】:

如果您使用Nuxt 并且有任何引发Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. 的外部脚本,您可以在下面找到解决方案。

【问题讨论】:

    标签: javascript vuejs2 vue-component nuxt.js


    【解决方案1】:

    解决方案 1 - 如果您需要全局脚本。

    就像使用其他脚本一样,只需使用vue-meta(已包含在 Nuxt 中)即可。添加到layouts/default.vue:

    <template>
      ...
    </template>
    
    <script>
      export default {
        ...
    
        head () {
          return {
            script: [
              {
                hid: 'any-label-for-the-script',
                src: 'SCRIPT_URL'
                // async: true,
                // defer: true
              }
            ]
          }
        },
    
        ...
    
        // If you need to run SOME_FUNCTION from downloaded script
        mounted () {
          // eslint-disable-next-line no-undef
          SOME_FUNCTION(param1, param2, ...)
        }
      }
    </script>
    

    解决方案 2 - 如果您只需要某个路由/组件上的脚本。

    1. 安装postscribe:npm install --save postscribe

    2. 创建带有内容的plugins/postscribe.client.js文件:

    import postscribe from 'postscribe'
    
    export default (context, inject) => {
      inject('postscribe', (elementId, scriptCode) => {
        postscribe(elementId, scriptCode)
      })
    }
    
    1. 在nuxt.config.js里面添加刚刚创建的文件:
    export default {
      ...
      plugins: [
        ...
    
        { src: '~/plugins/postscribe.client.js' }
    
        ...
      ],
      ...
    }
    
    1. 在您的组件中执行以下操作:
    <template>
      <div id="add-script-here" />
    </template>
    
    <script>
      ...
    
      mounted () {
        // eslint-disable-next-line no-useless-escape
        this.$postscribe('#add-script-here', '<script src="SCRIPT_URL"><\/script>')
    
        // If you need to do something onload, then instead of the line above do it like this:
        // this.$postscribe('#add-script-here', '<script onload="DO_SOMETHING_ONLOAD_HEAR" src="SCRIPT_URL"><\/script>')
      }
    
      ...
    </script>
    

    通常脚本应该添加到head或body,但似乎postscribe不能这样做,所以我们使用add-script-here。

    【讨论】:

      猜你喜欢
      • 2017-03-31
      • 2018-12-12
      • 2015-01-05
      • 2020-02-28
      • 2013-06-06
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多