Last Updated: November 27, 2016
· artchang
Photo sep 26  14 31 57

Preloading UIWebView or WKWebView in Swift


The key to preloading a WebView (either UIWebView or WKWebView), is to call viewDidLoad before the view appears. The trick is that in viewDidLoad you have the WKWebView or UIWebView ready to execute a loadRequest ahead of time. The first controller the app launches should perform the preload kick off.


  1. In your viewDidLoad override for the WebView controller, set the url and load the request (you can async this request to a background thread, but know that the request still happens in the main thread asynchronously, it shouldn't block).
  2. In the first controller (such as a MainTabBar or some intro screen you have), you will call the viewDidLoad of the WebView. Let's assume you do this in a UITabBarController. The controller YourWebViewController you see is a reference to your webview controller.


override func viewDidLoad() {
    // getWebViewController() is a helper that gets the right controller. You can implement this however you want, but you should
    //    easily be able to get this from the viewControllers on a UITabBarController or any other ViewController
    if let webViewController = getWebViewController() {
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            // this will asynchronously call the viewDidLoad, but will not layout everything yet and will not block the main thread
            // do not call webViewController.view.layoutIfNeeded() here, because that will block the main thread in a RELEASE mode, which sucks big time


override func viewDidLoad() {
  let url = ""
  let request = NSURLRequest(URL: url)
  // This webView is the UIWebView or WKWebView
Say Thanks