instantpage.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*! instant.page v0.0.0 - (C) 2019 Alexandre Dieulot - https://instant.page/license */
  2. let urlToPreload
  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. urlToPreload = linkElement.href
  21. mouseoverTimer = setTimeout(() => {
  22. preload(linkElement.href)
  23. mouseoverTimer = undefined
  24. }, 65)
  25. }
  26. function mouseoutListener(event) {
  27. if (event.relatedTarget && event.target.closest('a') == event.relatedTarget.closest('a')) {
  28. return
  29. }
  30. if (mouseoverTimer) {
  31. clearTimeout(mouseoverTimer)
  32. mouseoverTimer = undefined
  33. }
  34. else {
  35. urlToPreload = undefined
  36. stopPreloading()
  37. }
  38. }
  39. function isPreloadable(linkElement) {
  40. if (urlToPreload == linkElement.href) {
  41. return false
  42. }
  43. const urlObject = new URL(linkElement.href)
  44. if (urlObject.origin != location.origin) {
  45. return false
  46. }
  47. if (urlObject.pathname + urlObject.search == location.pathname + location.search && urlObject.hash) {
  48. return
  49. }
  50. if ('noInstant' in linkElement.dataset) {
  51. return false
  52. }
  53. return true
  54. }
  55. function preload(url) {
  56. prefetcher.href = url
  57. }
  58. function stopPreloading() {
  59. /* The spec says an empty string should abort the prefetching
  60. * but Firefox 64 interprets it as a relative URL to prefetch. */
  61. prefetcher.removeAttribute('href')
  62. }