Js determine whether loaded

Brief introduction

  Often used in the project js dynamic loading, is the way to create labels using js loaded, but because it is asynchronous code have a problem we need to perform some js after loading is complete, a variety of setTimeout, in fact, there is a problem , where the event is judged by whether js js loaded loaded

Code

Ado direct method on

// 传入需要加载的js地址 和 回调函数
function dynamicLoadJs(url, callback) {
  let head = document.getElementsByTagName('head')[0]
  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url
  if (typeof callback == 'function') {
    script.onload = script.onreadystatechange = function () {
      if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        callback()
        script.onload = script.onreadystatechange = null
      }
    }
  }
  head.appendChild(script)
}

Examples of Use

// 使用示例是不是很简单呢
dynamicLoadJs('//api.map.baidu.com/api?v=3.0',() => {
  // TO DO  进入回调则表示js已加载完成, 可以开始处理逻辑
})

Thank you for reading! If there are any errors in the article, or if you have a better understanding and suggestions, please contact me!

Published 29 original articles · won praise 18 · views 30000 +

Guess you like

Origin blog.csdn.net/Baby_lucy/article/details/105271576