2019-04-08 | 前端 | UNLOCK

`vue`模版文件动态插入 `script`的几种实现方法

vue 中模版文件动态插入 script的几种实现方法

业务场景:在业务中需要使用其他项目中的功能和方法,由于版本迭代的原因,需要实时更新当前项目中的版本信息

原生 JS 在 public/index.html 中动态插入 script

<!-- 在入口文件 `index.html` 中插入一下内容 -->
<script>
  ;(function() {
    var location = ....
    var src =
      document.location.protocol == 'http:'
        ? `http:${location}`
        : `https:${location}`
    var hm = document.createElement('script')
    hm.src = src
    hm.id = 'BearCrm'
    var s = document.getElementsByTagName('script')[0]
    s.parentNode.insertBefore(hm, s)
  })()
</script>

html-webpack-plugin 使用 lodash template 语法插入内容

  • <%= VALUE %> 用来做不转义插值;
  • <%- VALUE %> 用来做 HTML 转义插值;
  • <% expression %> 用来描述 JavaScript 流程控制。
// index.html
利于版本的迭代,其他关联项目中的版本迅速迭代
<script src="https:...?<%= Date.now() %>"></script>