Avoiding CSS Injection Delays in WKWebView iOS Swift Apps

Innovative business technology

When working with webviews in iOS, there are two key methods to be aware of when it comes to injecting CSS: didCommit and didStartProvisionalNavigation. Understanding the difference between these two methods is important for ensuring that your webview-based app behaves as expected.

The didCommit method is called when the webview has finished loading a new page. This means that the HTML and CSS for the new page have been fully loaded, and any JavaScript on the page has been executed. At this point, it is safe to inject CSS into the webview without the risk of it being overwritten by subsequent page loads.

On the other hand, the didStartProvisionalNavigation method is called when the webview has started loading a new page, but before the page has finished loading. This means that the HTML and CSS for the new page may not yet be fully loaded, and any JavaScript on the page may not yet have been executed. Injecting CSS into the webview at this point may result in your styles being overwritten by subsequent page loads, or potentially not being applied at all.

In general, it is best practice to inject CSS into a webview using the didCommit method, as this ensures that your styles will be applied correctly and will not be overwritten by subsequent page loads. However, there may be specific use cases where injecting CSS using the didStartProvisionalNavigation method is necessary, such as when you need to apply styles to a page before it has fully loaded.

In summary, it is important to understand the difference between didCommit and didStartProvisionalNavigation when working with webviews in iOS, and to choose the appropriate method for injecting CSS based on your specific use case. Using didCommit method is the best practice, as it ensure that your styles will be applied correctly and will not be overwritten by subsequent page loads.

BTW, WebViewGold for iOS uses didCommit method for Custom CSS Injection.