Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Dynamically get the script address of the page in js


May 30, 2021 Article blog


Table of contents


Foreword: (Business Logic)

In vue, in this case, the initialization loads too many js, resulting in the page white screen, in order to solve this situation, decided to use specific components to load the corresponding cdn address.
Why not vue on-demand loading, because our project on-demand performance requirements are very high, but on-demand loading, the introduction of plug-in packages, packaging after the size is much larger than cdn, the overall use of him is not worth the loss, but a single load of too many cdns will lead to white screen, so here I use the method: a specific page using a third-party plug-in, in the use of the page js dynamic loading scirpt, and label him

How to do this:

1, facing the first question, to get the current page used to all the introduction of the <script >, the following newArr is all the script address 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, All of Which We Put Directly in the #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, cannot be created, must wait for the page to load completely to mount)

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

Methods are defined 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)
      }
 
    },