instantpage.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*! instant.page v5.1.1 - (C) 2019-2022 Alexandre Dieulot - https://instant.page/license */
  2. let mouseoverTimer
  3. let lastTouchTimestamp
  4. const prefetches = new Set()
  5. const prefetchElement = document.createElement('link')
  6. const isSupported = prefetchElement.relList && prefetchElement.relList.supports && prefetchElement.relList.supports('prefetch')
  7. && window.IntersectionObserver && 'isIntersecting' in IntersectionObserverEntry.prototype
  8. const allowQueryString = 'instantAllowQueryString' in document.body.dataset
  9. const allowExternalLinks = 'instantAllowExternalLinks' in document.body.dataset
  10. const useWhitelist = 'instantWhitelist' in document.body.dataset
  11. const mousedownShortcut = 'instantMousedownShortcut' in document.body.dataset
  12. const DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION = 1111
  13. let delayOnHover = 65
  14. let useMousedown = false
  15. let useMousedownOnly = false
  16. let useViewport = false
  17. if ('instantIntensity' in document.body.dataset) {
  18. const intensity = document.body.dataset.instantIntensity
  19. if (intensity.substr(0, 'mousedown'.length) == 'mousedown') {
  20. useMousedown = true
  21. if (intensity == 'mousedown-only') {
  22. useMousedownOnly = true
  23. }
  24. }
  25. else if (intensity.substr(0, 'viewport'.length) == 'viewport') {
  26. if (!(navigator.connection && (navigator.connection.saveData || (navigator.connection.effectiveType && navigator.connection.effectiveType.includes('2g'))))) {
  27. if (intensity == "viewport") {
  28. /* Biggest iPhone resolution (which we want): 414 × 896 = 370944
  29. * Small 7" tablet resolution (which we don’t want): 600 × 1024 = 614400
  30. * Note that the viewport (which we check here) is smaller than the resolution due to the UI’s chrome */
  31. if (document.documentElement.clientWidth * document.documentElement.clientHeight < 450000) {
  32. useViewport = true
  33. }
  34. }
  35. else if (intensity == "viewport-all") {
  36. useViewport = true
  37. }
  38. }
  39. }
  40. else {
  41. const milliseconds = parseInt(intensity)
  42. if (!isNaN(milliseconds)) {
  43. delayOnHover = milliseconds
  44. }
  45. }
  46. }
  47. if (isSupported) {
  48. const eventListenersOptions = {
  49. capture: true,
  50. passive: true,
  51. }
  52. if (!useMousedownOnly) {
  53. document.addEventListener('touchstart', touchstartListener, eventListenersOptions)
  54. }
  55. if (!useMousedown) {
  56. document.addEventListener('mouseover', mouseoverListener, eventListenersOptions)
  57. }
  58. else if (!mousedownShortcut) {
  59. document.addEventListener('mousedown', mousedownListener, eventListenersOptions)
  60. }
  61. if (mousedownShortcut) {
  62. document.addEventListener('mousedown', mousedownShortcutListener, eventListenersOptions)
  63. }
  64. if (useViewport) {
  65. let triggeringFunction
  66. if (window.requestIdleCallback) {
  67. triggeringFunction = (callback) => {
  68. requestIdleCallback(callback, {
  69. timeout: 1500,
  70. })
  71. }
  72. }
  73. else {
  74. triggeringFunction = (callback) => {
  75. callback()
  76. }
  77. }
  78. triggeringFunction(() => {
  79. const intersectionObserver = new IntersectionObserver((entries) => {
  80. entries.forEach((entry) => {
  81. if (entry.isIntersecting) {
  82. const linkElement = entry.target
  83. intersectionObserver.unobserve(linkElement)
  84. preload(linkElement.href)
  85. }
  86. })
  87. })
  88. document.querySelectorAll('a').forEach((linkElement) => {
  89. if (isPreloadable(linkElement)) {
  90. intersectionObserver.observe(linkElement)
  91. }
  92. })
  93. })
  94. }
  95. }
  96. function touchstartListener(event) {
  97. /* Chrome on Android calls mouseover before touchcancel so `lastTouchTimestamp`
  98. * must be assigned on touchstart to be measured on mouseover. */
  99. lastTouchTimestamp = performance.now()
  100. const linkElement = event.target.closest('a')
  101. if (!isPreloadable(linkElement)) {
  102. return
  103. }
  104. preload(linkElement.href)
  105. }
  106. function mouseoverListener(event) {
  107. if (performance.now() - lastTouchTimestamp < DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION) {
  108. return
  109. }
  110. if (!('closest' in event.target)) {
  111. // Without this check sometimes an error “event.target.closest is not a function” is thrown, for unknown reasons
  112. // That error denotes that `event.target` isn’t undefined. My best guess is that it’s the Document.
  113. // Details could be gleaned from throwing such an error:
  114. //throw new TypeError(`instant.page non-element event target: timeStamp=${~~event.timeStamp}, type=${event.type}, typeof=${typeof event.target}, nodeType=${event.target.nodeType}, nodeName=${event.target.nodeName}, viewport=${innerWidth}x${innerHeight}, coords=${event.clientX}x${event.clientY}, scroll=${scrollX}x${scrollY}`)
  115. return
  116. }
  117. const linkElement = event.target.closest('a')
  118. if (!isPreloadable(linkElement)) {
  119. return
  120. }
  121. linkElement.addEventListener('mouseout', mouseoutListener, {passive: true})
  122. mouseoverTimer = setTimeout(() => {
  123. preload(linkElement.href)
  124. mouseoverTimer = undefined
  125. }, delayOnHover)
  126. }
  127. function mousedownListener(event) {
  128. const linkElement = event.target.closest('a')
  129. if (!isPreloadable(linkElement)) {
  130. return
  131. }
  132. preload(linkElement.href)
  133. }
  134. function mouseoutListener(event) {
  135. if (event.relatedTarget && event.target.closest('a') == event.relatedTarget.closest('a')) {
  136. return
  137. }
  138. if (mouseoverTimer) {
  139. clearTimeout(mouseoverTimer)
  140. mouseoverTimer = undefined
  141. }
  142. }
  143. function mousedownShortcutListener(event) {
  144. if (performance.now() - lastTouchTimestamp < DELAY_TO_NOT_BE_CONSIDERED_A_TOUCH_INITIATED_ACTION) {
  145. return
  146. }
  147. const linkElement = event.target.closest('a')
  148. if (event.which > 1 || event.metaKey || event.ctrlKey) {
  149. return
  150. }
  151. if (!linkElement) {
  152. return
  153. }
  154. linkElement.addEventListener('click', function (event) {
  155. if (event.detail == 1337) {
  156. return
  157. }
  158. event.preventDefault()
  159. }, {capture: true, passive: false, once: true})
  160. const customEvent = new MouseEvent('click', {view: window, bubbles: true, cancelable: false, detail: 1337})
  161. linkElement.dispatchEvent(customEvent)
  162. }
  163. function isPreloadable(linkElement) {
  164. if (!linkElement || !linkElement.href) {
  165. return
  166. }
  167. if (useWhitelist && !('instant' in linkElement.dataset)) {
  168. return
  169. }
  170. if (!allowExternalLinks && linkElement.origin != location.origin && !('instant' in linkElement.dataset)) {
  171. return
  172. }
  173. if (!['http:', 'https:'].includes(linkElement.protocol)) {
  174. return
  175. }
  176. if (linkElement.protocol == 'http:' && location.protocol == 'https:') {
  177. return
  178. }
  179. if (!allowQueryString && linkElement.search && !('instant' in linkElement.dataset)) {
  180. return
  181. }
  182. if (linkElement.hash && linkElement.pathname + linkElement.search == location.pathname + location.search) {
  183. return
  184. }
  185. if ('noInstant' in linkElement.dataset) {
  186. return
  187. }
  188. return true
  189. }
  190. function preload(url) {
  191. if (prefetches.has(url)) {
  192. return
  193. }
  194. const prefetcher = document.createElement('link')
  195. prefetcher.rel = 'prefetch'
  196. prefetcher.href = url
  197. document.head.appendChild(prefetcher)
  198. prefetches.add(url)
  199. }