Created
March 4, 2026 23:12
-
-
Save Nooshu/4427ed19a89e1e3e897db9902d1002bf to your computer and use it in GitHub Desktop.
The Web performance snippet I use to populate how quick a page loads on my blog, now fixed the iOS 0 milliseconds issue.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function() { | |
| /* check to see if the browser is modern enough to support the | |
| PerformanceNavigationTiming API */ | |
| if (!window.performance?.getEntriesByType) { | |
| console.warn('Performance API not supported'); | |
| return; | |
| } | |
| function showLoadTime() { | |
| const entries = performance.getEntriesByType('navigation'); | |
| const nav = entries[0]; | |
| if (!nav) return; | |
| // duration = loadEventEnd - startTime; on iOS/Safari it can be 0 if read too early | |
| // (PerformanceObserver can fire before load event). Fallbacks for when duration or | |
| // loadEventEnd is 0 (e.g. WebKit timing quirks, bfcache). | |
| let ms = nav.duration; | |
| if (!ms && nav.loadEventEnd > 0) { | |
| ms = nav.loadEventEnd - nav.startTime; | |
| } | |
| if (!ms && nav.domContentLoadedEventEnd > 0) { | |
| ms = nav.domContentLoadedEventEnd - nav.startTime; | |
| } | |
| if (typeof ms !== 'number' || !(ms >= 0)) return; | |
| const pageLoadTime = Math.floor(ms); | |
| let loadTimeElement = document.getElementById('pl'); | |
| if (!loadTimeElement) { | |
| loadTimeElement = document.createElement('p'); | |
| loadTimeElement.id = 'pl'; | |
| const footer = document.querySelector('footer'); | |
| if (footer) { | |
| footer.insertBefore(loadTimeElement, footer.firstChild); | |
| } | |
| } | |
| if (loadTimeElement) { | |
| loadTimeElement.textContent = `This page loaded in: ${pageLoadTime} milliseconds.`; | |
| } | |
| } | |
| // Read timing only after load event so loadEventEnd is set (fixes 0ms on iOS Safari). | |
| function runAfterLoad() { | |
| setTimeout(showLoadTime, 0); | |
| } | |
| if (document.readyState === 'complete') { | |
| runAfterLoad(); | |
| } else { | |
| window.addEventListener('load', runAfterLoad); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment