jsonp.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const chunks = {} // chunkId => exports
  2. const chunksInstalling = {} // chunkId => Promise
  3. const failedChunks = {}
  4. function importChunk(chunkId, src) {
  5. // Already installed
  6. if (chunks[chunkId]) {
  7. return Promise.resolve(chunks[chunkId])
  8. }
  9. // Failed loading
  10. if (failedChunks[chunkId]) {
  11. return Promise.reject(failedChunks[chunkId])
  12. }
  13. // Installing
  14. if (chunksInstalling[chunkId]) {
  15. return chunksInstalling[chunkId]
  16. }
  17. // Set a promise in chunk cache
  18. let resolve, reject
  19. const promise = chunksInstalling[chunkId] = new Promise((_resolve, _reject) => {
  20. resolve = _resolve
  21. reject = _reject
  22. })
  23. // Clear chunk data from cache
  24. delete chunks[chunkId]
  25. // Start chunk loading
  26. const script = document.createElement('script')
  27. script.charset = 'utf-8'
  28. script.timeout = 120
  29. script.src = src
  30. let timeout
  31. // Create error before stack unwound to get useful stacktrace later
  32. const error = new Error()
  33. // Complete handlers
  34. const onScriptComplete = script.onerror = script.onload = (event) => {
  35. // Cleanups
  36. clearTimeout(timeout)
  37. delete chunksInstalling[chunkId]
  38. // Avoid mem leaks in IE
  39. script.onerror = script.onload = null
  40. // Verify chunk is loaded
  41. if (chunks[chunkId]) {
  42. return resolve(chunks[chunkId])
  43. }
  44. // Something bad happened
  45. const errorType = event && (event.type === 'load' ? 'missing' : event.type)
  46. const realSrc = event && event.target && event.target.src
  47. error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'
  48. error.name = 'ChunkLoadError'
  49. error.type = errorType
  50. error.request = realSrc
  51. failedChunks[chunkId] = error
  52. reject(error)
  53. }
  54. // Timeout
  55. timeout = setTimeout(() => {
  56. onScriptComplete({ type: 'timeout', target: script })
  57. }, 120000)
  58. // Append script
  59. document.head.appendChild(script)
  60. // Return promise
  61. return promise
  62. }
  63. export function installJsonp() {
  64. window.__NUXT_JSONP__ = function (chunkId, exports) { chunks[chunkId] = exports }
  65. window.__NUXT_JSONP_CACHE__ = chunks
  66. window.__NUXT_IMPORT__ = importChunk
  67. }