Search code examples
iphoneioscocoa-touchuiwebview

Slow loading UIWebView from string


I am trying to load a UIWebView from a string as follows:

    NSString* plainContent = @"...";
    NSString* htmlContentString = [[NSString stringWithFormat:
                                   @"<html>"
                                   "<style type=\"text/css\">"
                                   "body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;}"
                                   "</style>"
                                   "<body>"
                                   "<p>%@</p>"
                                   "</body></html>", plainContent] retain];
    [webView loadHTMLString:htmlContentString baseURL:nil];

Where plain content has some simple HTML with about 5 links and 400 characters. I'm trying to run this on my iPhone5, and the first time it loads it always take a few seconds. Does anyone know why this is happening and how to fix this?


Solution

  • This usually happens because of CSS used in rendering web page. It is default behavior when loading page locally. We can also consider that in first load, UIWebview doesn't have cache to this and create cache for that page.

    To make it little fast try loading page from a file e.g.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"filePath" ofType:@"html" inDirectory:@"."]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    

    CSS like body { background-color:transparent; font-family:Arial-BoldMT; font-size:18;} also increase the time of loading a page.