Get the script address of the page dynamically in js, and dynamically add the script tag and address to him to solve the white screen problem of the page

Preface: (Business logic)

       In Vue, when encountering such a situation, too much js was initially loaded , resulting in a white screen on the page . In order to solve this situation, it was decided to use specific components to load the corresponding cdn address.

        Why not use vue 's on-demand loading ? Because our project has high performance requirements , but after on-demand loading, the imported plug-in package is much larger than cdn after packaging . On the whole, it is used. It’s not worth the loss, but loading too many CDNs at one time will cause a white screen, so here I use the method: a specific page uses a third-party plug-in, and the page js is used to dynamically load scirpt and label it

Specific operation:

1. Facing the first problem, we must first get all the imported <script> used in the current page.  The newArr below is all the script addresses obtained.

      let scriptsArr = document.getElementsByTagName('script')
      let newArr = []
      //获取所有的script地址
      for (var i = 0; i < scriptsArr.length; i++) {
        newArr.push(scriptsArr[i].getAttribute('src', 4))
      }

2. Load the cdn address we want to put in the interface, because vue is a single page component, so we put it directly on #app

      // 创建script标签,引入外部文件
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = url
        document.getElementById('app').appendChild(script)

Share source code:

Called in mounted: (must be mounted, not created, you must wait for the page to load before it can be mounted)

let url = '//cktcdn.kaoti100.com/cdn.jsdelivr.net/npm/vue-aplayer/vue-aplayer.js'
    this.app_script(url)//初始化给他添加cdn地址

Define methods in methods

 /**
     * 获取页面上的所有script地址。来判断是否要加cdn地址
     * */
    app_script(url) {
      let scriptsArr = document.getElementsByTagName('script')
      let newArr = []
      //获取所有的script地址
      for (var i = 0; i < scriptsArr.length; i++) {
        newArr.push(scriptsArr[i].getAttribute('src', 4))
      }
      let isFirst = true //判断是否加载过这个script,有就不加载了
      let cdnUrl = url
      newArr.forEach(item => {
        if (item === cdnUrl) {
          isFirst = false
        }
      })
      if (isFirst) {
        // 创建script标签,引入外部文件
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = url
        document.getElementById('app').appendChild(script)
      }

    },

That's it!

Guess you like

Origin blog.csdn.net/weixin_44727080/article/details/113696116