instantpage.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*! instant.page v0.0.0 - (C) 2019 Alexandre Dieulot - https://instant.page/license */
  2. let urlBeingPreloaded
  3. let mouseoverTimer
  4. const prefetcher = document.createElement('link')
  5. const isSupported = prefetcher.relList && prefetcher.relList.supports && prefetcher.relList.supports('prefetch')
  6. if (isSupported) {
  7. prefetcher.rel = 'prefetch'
  8. document.head.appendChild(prefetcher)
  9. document.addEventListener('mouseover', mouseoverListener, true)
  10. }
  11. function mouseoverListener(event) {
  12. const linkElement = event.target.closest('a')
  13. if (!linkElement) {
  14. return
  15. }
  16. if (!isPreloadable(linkElement)) {
  17. return
  18. }
  19. linkElement.addEventListener('mouseout', mouseoutListener)
  20. mouseoverTimer = setTimeout(preload, 65, linkElement.href)
  21. }
  22. function mouseoutListener(event) {
  23. if (event.relatedTarget && event.target.closest('a') == event.relatedTarget.closest('a')) {
  24. return
  25. }
  26. stopPreloading()
  27. }
  28. function isPreloadable(linkElement) {
  29. if (urlBeingPreloaded == linkElement.href) {
  30. return false
  31. }
  32. const urlObject = new URL(linkElement.href)
  33. if (urlObject.origin != location.origin) {
  34. return false
  35. }
  36. if (urlObject.pathname + urlObject.search == location.pathname + location.search && urlObject.hash) {
  37. return
  38. }
  39. if ('noInstant' in linkElement.dataset) {
  40. return false
  41. }
  42. return true
  43. }
  44. function preload(url) {
  45. urlBeingPreloaded = url
  46. prefetcher.href = url
  47. }
  48. function stopPreloading() {
  49. if (mouseoverTimer) {
  50. clearTimeout(mouseoverTimer)
  51. mouseoverTimer = undefined
  52. }
  53. if (!urlBeingPreloaded) {
  54. return
  55. }
  56. urlBeingPreloaded = undefined
  57. /* The spec says an empty string should abort the prefetching
  58. * but Firefox 64 interprets it as a relative URL to prefetch. */
  59. prefetcher.removeAttribute('href')
  60. }