js代码动态加载和删除js、css、image文件方法记录

2022/03/02 Javascript 共 2316 字,约 7 分钟
北城北小北

目前在项目中是使用了一些动态加载和删除js、css、image资源的方法,记录下来

加载和删除JS文件

export function LoadJS (url, callback, errcallback) {
  var documentHeader = document.head || document.getElementsByTagName('head')[0]
  // 防止单页应用加载多次
  var addSign = true
  var scripts = document.getElementsByTagName('script')
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i] && scripts[i].src && scripts[i].src.indexOf(url) != -1) {
      addSign = false
    }
  }
  if (addSign) {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.charset = 'utf-8'
    script.async = true
    script.src = url
    documentHeader.appendChild(script)
    script.onload = function () {
      callback && callback()
    }
    script.onerror = function () {
      errcallback && errcallback()
      documentHeader.removeChild(script)
    }
  } else {
    callback && callback()
  }
}

// js删除script
export function removeScript(src) {
  var scripts = document.getElementsByTagName('script')
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i] && scripts[i].src && scripts[i].src.indexOf(src) != -1) {
      scripts[i].parentNode.removeChild(scripts[i])
    }
  }
}

动态加载和删除css文件

// 加载CSS引用
export function LoadLink (url) {
  // 防止单页应用加载多条
  var addSign = true
  var links = document.getElementsByTagName('link')
  for (var i = 0; i < links.length; i++) {
    if (links[i] && links[i].href && links[i].href.indexOf(url) != -1) {
      addSign = false
    }
  }
  if (addSign) {
    var link = document.createElement('link')
    link.type = 'text/css'
    link.rel = 'stylesheet'
    link.href = url
    document.getElementsByTagName('head')[0].appendChild(link)
  }
}

// 加载CSS
export function LoadCss (id, content) {
  var newStyle = document.createElement('style')
  newStyle.type = 'text/css'
  newStyle.id = id
  if (typeof newStyle.styleSheet != 'undefined') {
    newStyle.styleSheet.cssText = content
  } else {
    newStyle.innerHTML = content
  }
  // 防止加载多次
  var addSign = true
  var styles = document.getElementsByTagName('style')
  for (var i = 0; i < styles.length; i++) {
    if (styles[i] && styles[i].id && styles[i].id == id) {
      addSign = false
    }
  }
  if (addSign) {
    document.getElementsByTagName('head')[0].appendChild(newStyle)
  }
}

// js删除link文件
export function removelink(href) {
  var links = document.getElementsByTagName('link')
  for (var i = 0; i < links.length; i++) {
    if (links[i] && links[i].href && links[i].href.indexOf(href) != -1) {
      links[i].parentNode.removeChild(links[i])
    }
  }
}

加载img

export function loadIamge(imageUrl,successCallback,errorCallback){
    let img = new Image()
    img.src = imageUrl
    img.onload = () =>{
        successCallback()
    }
    img.onerror = (e) =>{
        errorCallback(e)
    }
}

文档信息

Search

    Table of Contents