remoteLoad.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. export default function remoteLoad (url, hasCallback) {
  2. return createScript(url)
  3. /**
  4. * 创建script
  5. * @param url
  6. * @returns {Promise}
  7. */
  8. function createScript (url) {
  9. let scriptElement = document.createElement('script')
  10. document.body.appendChild(scriptElement)
  11. let promise = new Promise((resolve, reject) => {
  12. scriptElement.addEventListener('load', e => {
  13. removeScript(scriptElement)
  14. if (!hasCallback) {
  15. resolve(e)
  16. }
  17. }, false)
  18. scriptElement.addEventListener('error', e => {
  19. removeScript(scriptElement)
  20. reject(e)
  21. }, false)
  22. if (hasCallback) {
  23. window.____callback____ = function () {
  24. resolve()
  25. window.____callback____ = null
  26. }
  27. }
  28. })
  29. if (hasCallback) {
  30. url += '&callback=____callback____'
  31. }
  32. scriptElement.src = url
  33. return promise
  34. }
  35. /**
  36. * 移除script标签
  37. * @param scriptElement script dom
  38. */
  39. function removeScript (scriptElement) {
  40. document.body.removeChild(scriptElement)
  41. }
  42. }