判斷一個腳本已經加載完畢的方法

export const appendScriptReady = (url, onReadyCallback) => {
  const targetScript = document.createElement('script')
  targetScript.type = 'text/javascript'
  if (targetScript.readyState) { // IE 6,7,8
    targetScript.onreadystatechange = () => {
      if (targetScript.readyState === 'loaded' ||
        targetScript.readyState === 'complete') {
        targetScript.onreadystatechange = null
        onReadyCallback()
      }
    }
  } else { // Not IE
    targetScript.onload = () => {
      onReadyCallback()
    }
  }

  targetScript.src = url
  document.head.appendChild(targetScript)
}
相關文章
相關標籤/搜索