remoteLoad.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. }