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?
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.
I recently struggled with UIWebView performance. It seemed to take a very long time to process the local HTML I was providing (1 or 2 seconds on iPad Air 2 simulator) even if it was ridiculously small.
After a lot of googling around, I found that the culprit was the phone numbers detection on webview. Once I unchecked it on the storyboard, the latency was gone.
Hope it helps someone facing the same issue :)
For other who experienced this problems, sometimes we created HTML file by copy-paste-ing from existing websites and we're forget to check the links on header.
In my case, I forgot to remove unused link rel in my html string header:
NSString* html = [NSString stringWithFormat:@"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>%@</title><link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" /></head><body><h1 style=\"font-size: 2em; margin-bottom: 0; color: #3357b8; font-weight: bold\">%@</h1><div style=\"color: #555\">%@</div><br><p style=\"line-height: 1.7em\">%@</p><a href=\"%@\"><b>Open in browser</b></a><br></body></html>", title, title, dateString, content, detail];
The local URL pointed by above link rel make loading time even worst.
<link type=\"text/css\" rel=\"stylesheet\" href=\"http://192.168.3.183/assets/css/question.css?1383042738\" />
Just don't forget to re-check your header or other link in your HTML string and remove it if it is not used.