How to dynamically obtain the script address of a page in js
This article mainly explains "how to dynamically obtain the script address of the page in js". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to dynamically obtain the script address of the page in js"!
Preface: (business logic) in vue, encounter such a situation, initialization load too much js, resulting in white screen page, in order to solve this situation, decided to use specific components to load the corresponding cdn address.
Why not vue on-demand load it, because our project performance requirements are very high, but on-demand load, the introduction of plug-in package, packaged size is much larger than cdn, the overall use of him is not worth the loss, but loading too much cdn at one time will lead to white screen, so here I use the method: a specific page using third-party plug-ins, in the use of page js dynamic load scrpt, and give him the label Specific operation: 1. Facing the first problem, we must first obtain all the imported ones used by the current page. The newArr below is all the script addresses we have obtained. let scriptsArr = document.getElementsByTagName ('script ') let newArr = [] //Get all script addresses for (var i = 0; i
< scriptsArr.length; i++) { newArr.push(scriptsArr[i].getAttribute('src', 4)) }2、给界面加载我们想放进去的 cdn 地址,因为 vue 是单页面组件,所有我们直接放在 #app上// 创建script标签,引入外部文件 let script = document.createElement('script') script.type = 'text/javascript' script.src = url document.getElementById('app').appendChild(script)分享源码: mounted 中调用:(必须是 mounted,不能是 created,必须等页面加载完成才能挂载) let url = '//cktcdn.kaoti100.com/cdn.jsdelivr.net/npm/vue-aplayer/vue-aplayer.js' this.app_script(url)//初始化给他添加cdn地址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) { //Create script tags, import external files let script = document.createElement('script') script.type = 'text/javascript' script.src = url document.getElementById('app').appendChild(script) } }, At this point, I believe that everyone has a deeper understanding of "how to dynamically obtain the script address of the page in js", may wish to actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!