export default function remoteLoad (url, hasCallback) {
  return createScript(url)

  function createScript (url) {
    var scriptElement = document.createElement('script')
    document.head.appendChild(scriptElement)
    var promise = new Promise((resolve, reject) => {
      scriptElement.addEventListener('load', e => {
        var has = document.body.contains(scriptElement)
        if(has) removeScript(scriptElement)
        if (!hasCallback) {
          resolve(e)
        }
      }, false)

      scriptElement.addEventListener('error', e => {
        removeScript(scriptElement)
        reject(e)
      }, false)

      if (hasCallback) {
        window.____callback____ = function () {
          resolve()
          window.____callback____ = null
        }
      }
    })

    if (hasCallback) {
      url += '&callback=____callback____'
    }

    scriptElement.src = url

    return promise
  }

  function removeScript (scriptElement) {
    document.body.removeChild(scriptElement)
  }

}