Last active
October 3, 2024 05:13
-
-
Save lanserxt/eaec4ab76e04c58d55d78c84f98cd6b1 to your computer and use it in GitHub Desktop.
WKWebView script for full content loading
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
//Setting the script | |
extension WebViewCoordinator: WKNavigationDelegate { | |
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { | |
let script = """ | |
function isContentFullyRendered() { | |
var imgElements = document.images; | |
var imgComplete = true; | |
for (var i = 0; i < imgElements.length; i++) { | |
if (!imgElements[i].complete) { | |
imgComplete = false; | |
break; | |
} | |
} | |
var fontComplete = document.fonts.status === 'loaded'; | |
if (imgComplete && fontComplete) { | |
window.webkit.messageHandlers.renderingFinished.postMessage('Rendering Complete'); | |
} | |
} | |
document.addEventListener('DOMContentLoaded', isContentFullyRendered); | |
window.addEventListener('load', isContentFullyRendered); | |
document.fonts.addEventListener('loadingdone', isContentFullyRendered); | |
isContentFullyRendered(); | |
""" | |
let renderingCheckScript = """ | |
\(script) | |
""" | |
webView.evaluateJavaScript(renderingCheckScript, completionHandler: nil) | |
} | |
} | |
//Tracking the message handler | |
extension WebViewCoordinator: WKScriptMessageHandler { | |
// Message handler function | |
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { | |
//This is our event! | |
if message.name == "renderingFinished" { | |
print("Content fully rendered!") | |
} | |
} | |
} | |
//And just link all handlers on init | |
let contentController = WKUserContentController() | |
contentController.add(context.coordinator, name: "renderingFinished") | |
let config = WKWebViewConfiguration() | |
config.userContentController = contentController | |
return WKWebView(frame:.zero, configuration: config) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment