Last active
August 29, 2015 14:06
-
-
Save morganney/79618ab71fdbd0f64b19 to your computer and use it in GitHub Desktop.
A Nested JSON Hierarchy by Type from Resource Performance Entries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getJSONResourceHierachy() { | |
| var images = {png: 1, jpg: 1, jpeg: 1, gif: 1, tif: 1, tiff: 1, bmp: 1, ico: 1, svg: 1} | |
| , entries = window.performance.getEntriesByType('resource') | |
| , length = entries.length | |
| , archy = {} | |
| , entry = undefined | |
| , name = undefined | |
| , mt = undefined | |
| ; | |
| // helper function for grouping by media type | |
| function groupByMediaType(mt, entry) { | |
| if(mt === 'css') archy.children[2].children.push(entry); | |
| else if(mt === 'js') archy.children[0].children.push(entry); | |
| else if(mt in images) archy.children[1].children.push(entry); | |
| else archy.children[3].children.push(entry); | |
| } | |
| // the D3 treemap hierarchy root node | |
| archy.name = 'Resource Entries'; | |
| archy.children = [ | |
| {name: 'JavaScript', children: []}, | |
| {name: 'Image', children: []}, | |
| {name: 'CSS', children: []}, | |
| {name: 'Other', children: []} | |
| ]; | |
| for(var i = 0; i < length; i++) { | |
| // attempt to determine the media type from filename | |
| entry = entries[i]; | |
| name = entry.name; | |
| mt = name.split('.'); | |
| mt = mt[mt.length - 1].toLowerCase(); | |
| // add some useful networking metrics | |
| entry.appCache = entry.domainLookupStart - entry.fetchStart; | |
| entry.dns = entry.domainLookupEnd - entry.domainLookupStart; | |
| entry.tcp = entry.connectEnd - entry.connectStart; | |
| entry.request = entry.responseStart - entry.requestStart; | |
| entry.response = entry.responseEnd - entry.responseStart; | |
| entry.ttfb = entry.responseStart - entry.startTime; | |
| // satisfy default d3 treemap value accessor | |
| entry.value = entry.duration; | |
| // determine entries grouping | |
| // @see http://www.w3.org/TR/resource-timing/#dom-performanceresourcetiming-initiatortype | |
| switch(entry.initiatorType.toLowerCase()) { | |
| case 'link': // don't assume it's a css file, actually inspect. | |
| groupByMediaType(mt, entry); | |
| break; | |
| case 'script': | |
| archy.children[0].children.push(entry); | |
| break; | |
| case 'img': | |
| archy.children[1].children.push(entry); | |
| break; | |
| case 'css': // could be img or css file (url() syntax in css file) | |
| groupByMediaType(mt, entry); | |
| break; | |
| case 'xmlhttprequest': | |
| archy.children[3].children.push(entry); | |
| break; | |
| default: groupByMediaType(mt, entry); | |
| } | |
| } | |
| return JSON.stringify(archy); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment