ios wkwebview,监控H5页面css,js,image资源文件的加载时间与页面总加载时间
由于公司提了一的新的任务,需要在web页面监控css,js,image的加载时间,研究一下,下面是可以实现监控的。在wkwebview代理方法didFinishNavigation中添加以下代码。
由于公司提了一的新的任务,需要在web页面监控css,js,image的加载时间,研究一下,下面是可以实现监控的。
在wkwebview代理方法didFinishNavigation中添加以下代码
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSString *script = @"var result = {\
resources: [],\
duration: null\
};\
var timing = performance.timing;\
var pageloadtime = timing.loadEventEnd - timing.navigationStart;\
var resources = performance.getEntriesByType('resource');\
var filteredResources = resources.filter(function(resource) {\
var type = resource.initiatorType;\
return (type === 'link' && resource.name.match(/\\.css$/)) ||\
(type === 'script' && resource.name.match(/\\.js$/)) ||\
(type === 'img' && resource.name.match(/\\.(png|jpg|jpeg|gif|webp|bmp)$/));\
});\
if (resources && resources.length > 0) {\
for (var i = 0; i < resources.length; i++) {\
var resource = resources[i];\
result.resources.push({\
name: resource.name,\
duration: resource.duration,\
size: resource.encodedBodySize,\
initiatorType:resource.initiatorType\
});\
}\
}\
result.duration = timing.loadEventEnd - timing.navigationStart;\
result;";
[webView evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
if (!error && [result isKindOfClass:[NSDictionary class]]) {
NSArray *resources = result[@"resources"];
NSTimeInterval duration = [result[@"duration"] doubleValue];
NSLog(@"Page loaded in %fms", duration);
for (NSDictionary *resource in resources) {
NSString *name = resource[@"name"];
NSTimeInterval resourceDuration = [resource[@"duration"] doubleValue];
NSInteger resourceSize = [resource[@"size"] integerValue];
NSString *initiatorType = resource[@"initiatorType"];
NSLog(@"Resource loaded: %@, duration: %fms, size: %ld bytes, initiatorType:%@", name, resourceDuration, (long)resourceSize,initiatorType);
}
} else {
NSLog(@"Failed to evaluate JavaScript: %@", error);
}
}];
}
更多推荐
所有评论(0)