动态引入的背景

在vue项目开发中只有一个index.html 

这个时候,如果我们要做到只在指定路由组件加载的时候,才加载指定的外部js 

并且在离开指定路由或者组件的时候,删除掉引入的js

动态引入

    const scriptInfo = document.createElement("script")
    s.type = "text/javascript"
    scriptInfo.setAttribute("data-callType","callScript")
    scriptInfo.src = "需要引入的js路径"
    document.head.appendChild(scriptInfo)
  • 使用document.createElement 创建指定元素
  • setAttribute 动态设置属性
  • document.head 获取 head
  • 使用appendChild 添加 script 到  head中

动态删除


    let callScript = document.querySelector("script[data-callType='callScript']")
    document.head.removeChild(callScript)
  • 使用document.querySelector 获取到元素
  • 使用removeChild 删除元素
     

Logo

前往低代码交流专区

更多推荐