Skip to content

Instantly share code, notes, and snippets.

@KunalKumarSwift
Last active May 22, 2025 17:37
Show Gist options
  • Save KunalKumarSwift/9a4edc1338216783308c1ae3abeaba9b to your computer and use it in GitHub Desktop.
Save KunalKumarSwift/9a4edc1338216783308c1ae3abeaba9b to your computer and use it in GitHub Desktop.
WebView Performance
import SwiftUI
@main
struct WebTimingApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
WebView(url: URL(string: "https://google.com")!)
.edgesIgnoringSafeArea(.all)
}
}
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
let url: URL
func makeCoordinator() -> Coordinator {
Coordinator()
}
func makeUIView(context: Context) -> WKWebView {
let contentController = WKUserContentController()
contentController.add(context.coordinator, name: "onLoadTime")
// Inject JS to record window.onload timestamp
let js = """
window.addEventListener('load', () => {
const onLoadTime = performance.now();
window.webkit.messageHandlers.onLoadTime.postMessage(onLoadTime);
});
"""
let userScript = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(userScript)
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = context.coordinator
let request = URLRequest(url: url)
webView.load(request)
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
private var onLoadTime: Double?
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "onLoadTime", let time = message.body as? Double {
self.onLoadTime = time
print("onload event fired at \(time) ms")
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let finishTime = Date().timeIntervalSince1970 * 1000 // in ms
if let onLoadTime = self.onLoadTime {
let loadDuration = finishTime - onLoadTime
print("Time from window.onload to didFinish: \(loadDuration) ms")
} else {
print("onload time not yet captured")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment