prefetch.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Warning: this could cause some memory leaks
  2. let prefetches = {}
  3. export function prefetchHtml(destination, callback) {
  4. let path = destination.pathname
  5. if (prefetches[path]) return
  6. prefetches[path] = { finished: false, html: null, whenFinished: () => {} }
  7. fetch(path).then(i => i.text()).then(html => {
  8. callback(html)
  9. })
  10. }
  11. export function storeThePrefetchedHtmlForWhenALinkIsClicked(html, destination) {
  12. let state = prefetches[destination.pathname]
  13. state.html = html
  14. state.finished = true
  15. state.whenFinished()
  16. }
  17. export function getPretchedHtmlOr(destination, receive, ifNoPrefetchExists) {
  18. let path = destination.pathname
  19. if (! prefetches[path]) return ifNoPrefetchExists()
  20. if (prefetches[path].finished) {
  21. let html = prefetches[path].html
  22. delete prefetches[path]
  23. return receive(html)
  24. } else {
  25. prefetches[path].whenFinished = () => {
  26. let html = prefetches[path].html
  27. delete prefetches[path]
  28. receive(html)
  29. }
  30. }
  31. }