Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(117)

Side by Side Diff: chrome_linux64/resources/inspector/AuditsPanel.js

Issue 310483004: Roll reference builds to 35.0.1916.114. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/deps/reference_builds/
Patch Set: Created 6 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 WebInspector.AuditsPanel=function() 1 WebInspector.AuditsPanel=function()
2 {WebInspector.Panel.call(this,"audits");this.registerRequiredCSS("panelEnablerVi ew.css");this.registerRequiredCSS("auditsPanel.css");this.createSidebarViewWithT ree();this.splitView.mainElement().classList.add("vbox");this.auditsTreeElement= new WebInspector.SidebarSectionTreeElement("",{},true);this.sidebarTree.appendCh ild(this.auditsTreeElement);this.auditsTreeElement.listItemElement.classList.add ("hidden");this.auditsItemTreeElement=new WebInspector.AuditsSidebarTreeElement( this);this.auditsTreeElement.appendChild(this.auditsItemTreeElement);this.auditR esultsTreeElement=new WebInspector.SidebarSectionTreeElement(WebInspector.UIStri ng("RESULTS"),{},true);this.sidebarTree.appendChild(this.auditResultsTreeElement );this.auditResultsTreeElement.expand();this._constructCategories();this._auditC ontroller=new WebInspector.AuditController(this);this._launcherView=new WebInspe ctor.AuditLauncherView(this._auditController);for(var id in this.categoriesById) 2 {WebInspector.PanelWithSidebarTree.call(this,"audits");this.registerRequiredCSS( "panelEnablerView.css");this.registerRequiredCSS("auditsPanel.css");this.auditsT reeElement=new WebInspector.SidebarSectionTreeElement("",{},true);this.sidebarTr ee.appendChild(this.auditsTreeElement);this.auditsTreeElement.listItemElement.cl assList.add("hidden");this.auditsItemTreeElement=new WebInspector.AuditsSidebarT reeElement(this);this.auditsTreeElement.appendChild(this.auditsItemTreeElement); this.auditResultsTreeElement=new WebInspector.SidebarSectionTreeElement(WebInspe ctor.UIString("RESULTS"),{},true);this.sidebarTree.appendChild(this.auditResults TreeElement);this.auditResultsTreeElement.expand();this._constructCategories();t his._auditController=new WebInspector.AuditController(this);this._launcherView=n ew WebInspector.AuditLauncherView(this._auditController);for(var id in this.cate goriesById)
3 this._launcherView.addCategory(this.categoriesById[id]);} 3 this._launcherView.addCategory(this.categoriesById[id]);}
4 WebInspector.AuditsPanel.prototype={canSearch:function() 4 WebInspector.AuditsPanel.prototype={canSearch:function()
5 {return false;},get categoriesById() 5 {return false;},get categoriesById()
6 {return this._auditCategoriesById;},addCategory:function(category) 6 {return this._auditCategoriesById;},addCategory:function(category)
7 {this.categoriesById[category.id]=category;this._launcherView.addCategory(catego ry);},getCategory:function(id) 7 {this.categoriesById[category.id]=category;this._launcherView.addCategory(catego ry);},getCategory:function(id)
8 {return this.categoriesById[id];},_constructCategories:function() 8 {return this.categoriesById[id];},_constructCategories:function()
9 {this._auditCategoriesById={};for(var categoryCtorID in WebInspector.AuditCatego ries){var auditCategory=new WebInspector.AuditCategories[categoryCtorID]();audit Category._id=categoryCtorID;this.categoriesById[categoryCtorID]=auditCategory;}} ,auditFinishedCallback:function(mainResourceURL,results) 9 {this._auditCategoriesById={};for(var categoryCtorID in WebInspector.AuditCatego ries){var auditCategory=new WebInspector.AuditCategories[categoryCtorID]();audit Category._id=categoryCtorID;this.categoriesById[categoryCtorID]=auditCategory;}} ,auditFinishedCallback:function(mainResourceURL,results)
10 {var children=this.auditResultsTreeElement.children;var ordinal=1;for(var i=0;i< children.length;++i){if(children[i].mainResourceURL===mainResourceURL) 10 {var children=this.auditResultsTreeElement.children;var ordinal=1;for(var i=0;i< children.length;++i){if(children[i].mainResourceURL===mainResourceURL)
11 ordinal++;} 11 ordinal++;}
12 var resultTreeElement=new WebInspector.AuditResultSidebarTreeElement(this,result s,mainResourceURL,ordinal);this.auditResultsTreeElement.appendChild(resultTreeEl ement);resultTreeElement.revealAndSelect();},showResults:function(categoryResult s) 12 var resultTreeElement=new WebInspector.AuditResultSidebarTreeElement(this,result s,mainResourceURL,ordinal);this.auditResultsTreeElement.appendChild(resultTreeEl ement);resultTreeElement.revealAndSelect();},showResults:function(categoryResult s)
13 {if(!categoryResults._resultView) 13 {if(!categoryResults._resultView)
14 categoryResults._resultView=new WebInspector.AuditResultView(categoryResults);th is.visibleView=categoryResults._resultView;},showLauncherView:function() 14 categoryResults._resultView=new WebInspector.AuditResultView(categoryResults);th is.visibleView=categoryResults._resultView;},showLauncherView:function()
15 {this.visibleView=this._launcherView;},get visibleView() 15 {this.visibleView=this._launcherView;},get visibleView()
16 {return this._visibleView;},set visibleView(x) 16 {return this._visibleView;},set visibleView(x)
17 {if(this._visibleView===x) 17 {if(this._visibleView===x)
18 return;if(this._visibleView) 18 return;if(this._visibleView)
19 this._visibleView.detach();this._visibleView=x;if(x) 19 this._visibleView.detach();this._visibleView=x;if(x)
20 this.splitView.setMainView(x);},wasShown:function() 20 x.show(this.mainElement());},wasShown:function()
21 {WebInspector.Panel.prototype.wasShown.call(this);if(!this._visibleView) 21 {WebInspector.Panel.prototype.wasShown.call(this);if(!this._visibleView)
22 this.auditsItemTreeElement.select();},clearResults:function() 22 this.auditsItemTreeElement.select();},clearResults:function()
23 {this.auditsItemTreeElement.revealAndSelect();this.auditResultsTreeElement.remov eChildren();},__proto__:WebInspector.Panel.prototype} 23 {this.auditsItemTreeElement.revealAndSelect();this.auditResultsTreeElement.remov eChildren();},__proto__:WebInspector.PanelWithSidebarTree.prototype}
24 WebInspector.AuditCategoryImpl=function(displayName) 24 WebInspector.AuditCategoryImpl=function(displayName)
25 {this._displayName=displayName;this._rules=[];} 25 {this._displayName=displayName;this._rules=[];}
26 WebInspector.AuditCategoryImpl.prototype={get id() 26 WebInspector.AuditCategoryImpl.prototype={get id()
27 {return this._id;},get displayName() 27 {return this._id;},get displayName()
28 {return this._displayName;},addRule:function(rule,severity) 28 {return this._displayName;},addRule:function(rule,severity)
29 {rule.severity=severity;this._rules.push(rule);},run:function(requests,ruleResul tCallback,categoryDoneCallback,progress) 29 {rule.severity=severity;this._rules.push(rule);},run:function(requests,ruleResul tCallback,categoryDoneCallback,progress)
30 {this._ensureInitialized();var remainingRulesCount=this._rules.length;progress.s etTotalWork(remainingRulesCount);function callbackWrapper(result) 30 {this._ensureInitialized();var remainingRulesCount=this._rules.length;progress.s etTotalWork(remainingRulesCount);function callbackWrapper(result)
31 {ruleResultCallback(result);progress.worked();if(!--remainingRulesCount) 31 {ruleResultCallback(result);progress.worked();if(!--remainingRulesCount)
32 categoryDoneCallback();} 32 categoryDoneCallback();}
33 for(var i=0;i<this._rules.length;++i) 33 for(var i=0;i<this._rules.length;++i)
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
90 {this.addRule(new WebInspector.AuditRules.UnusedCssRule(),WebInspector.AuditRule .Severity.Warning);this.addRule(new WebInspector.AuditRules.CssInHeadRule(),WebI nspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.Sty lesScriptsOrderRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new W ebInspector.AuditRules.VendorPrefixedCSSProperties(),WebInspector.AuditRule.Seve rity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype} 90 {this.addRule(new WebInspector.AuditRules.UnusedCssRule(),WebInspector.AuditRule .Severity.Warning);this.addRule(new WebInspector.AuditRules.CssInHeadRule(),WebI nspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.Sty lesScriptsOrderRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new W ebInspector.AuditRules.VendorPrefixedCSSProperties(),WebInspector.AuditRule.Seve rity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype}
91 WebInspector.AuditCategories.NetworkUtilization=function(){WebInspector.AuditCat egoryImpl.call(this,WebInspector.AuditCategories.NetworkUtilization.AuditCategor yName);} 91 WebInspector.AuditCategories.NetworkUtilization=function(){WebInspector.AuditCat egoryImpl.call(this,WebInspector.AuditCategories.NetworkUtilization.AuditCategor yName);}
92 WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName=WebInspector.U IString("Network Utilization");WebInspector.AuditCategories.NetworkUtilization.p rototype={initialize:function() 92 WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName=WebInspector.U IString("Network Utilization");WebInspector.AuditCategories.NetworkUtilization.p rototype={initialize:function()
93 {this.addRule(new WebInspector.AuditRules.GzipRule(),WebInspector.AuditRule.Seve rity.Severe);this.addRule(new WebInspector.AuditRules.ImageDimensionsRule(),WebI nspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.Co okieSizeRule(400),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebI nspector.AuditRules.StaticCookielessRule(5),WebInspector.AuditRule.Severity.Warn ing);this.addRule(new WebInspector.AuditRules.CombineJsResourcesRule(2),WebInspe ctor.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.Combine CssResourcesRule(2),WebInspector.AuditRule.Severity.Severe);this.addRule(new Web Inspector.AuditRules.MinimizeDnsLookupsRule(4),WebInspector.AuditRule.Severity.W arning);this.addRule(new WebInspector.AuditRules.ParallelizeDownloadRule(4,10,0. 5),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditR ules.BrowserCacheControlRule(),WebInspector.AuditRule.Severity.Severe);this.addR ule(new WebInspector.AuditRules.ProxyCacheControlRule(),WebInspector.AuditRule.S everity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype};WebInspec tor.AuditController=function(auditsPanel) 93 {this.addRule(new WebInspector.AuditRules.GzipRule(),WebInspector.AuditRule.Seve rity.Severe);this.addRule(new WebInspector.AuditRules.ImageDimensionsRule(),WebI nspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.Co okieSizeRule(400),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebI nspector.AuditRules.StaticCookielessRule(5),WebInspector.AuditRule.Severity.Warn ing);this.addRule(new WebInspector.AuditRules.CombineJsResourcesRule(2),WebInspe ctor.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.Combine CssResourcesRule(2),WebInspector.AuditRule.Severity.Severe);this.addRule(new Web Inspector.AuditRules.MinimizeDnsLookupsRule(4),WebInspector.AuditRule.Severity.W arning);this.addRule(new WebInspector.AuditRules.ParallelizeDownloadRule(4,10,0. 5),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditR ules.BrowserCacheControlRule(),WebInspector.AuditRule.Severity.Severe);this.addR ule(new WebInspector.AuditRules.ProxyCacheControlRule(),WebInspector.AuditRule.S everity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype};WebInspec tor.AuditController=function(auditsPanel)
94 {this._auditsPanel=auditsPanel;WebInspector.resourceTreeModel.addEventListener(W ebInspector.ResourceTreeModel.EventTypes.Load,this._didMainResourceLoad,this);} 94 {this._auditsPanel=auditsPanel;WebInspector.resourceTreeModel.addEventListener(W ebInspector.ResourceTreeModel.EventTypes.Load,this._didMainResourceLoad,this);}
95 WebInspector.AuditController.prototype={_executeAudit:function(categories,result Callback) 95 WebInspector.AuditController.prototype={_executeAudit:function(categories,result Callback)
96 {this._progress.setTitle(WebInspector.UIString("Running audit"));function ruleRe sultReadyCallback(categoryResult,ruleResult) 96 {this._progress.setTitle(WebInspector.UIString("Running audit"));function ruleRe sultReadyCallback(categoryResult,ruleResult)
97 {if(ruleResult&&ruleResult.children) 97 {if(ruleResult&&ruleResult.children)
98 categoryResult.addRuleResult(ruleResult);if(this._progress.isCanceled()) 98 categoryResult.addRuleResult(ruleResult);if(this._progress.isCanceled())
99 this._progress.done();} 99 this._progress.done();}
100 var results=[];var mainResourceURL=WebInspector.inspectedPageURL;var categoriesD one=0;function categoryDoneCallback() 100 var results=[];var mainResourceURL=WebInspector.resourceTreeModel.inspectedPageU RL();var categoriesDone=0;function categoryDoneCallback()
101 {if(++categoriesDone!==categories.length) 101 {if(++categoriesDone!==categories.length)
102 return;this._progress.done();resultCallback(mainResourceURL,results)} 102 return;this._progress.done();resultCallback(mainResourceURL,results)}
103 var requests=WebInspector.networkLog.requests.slice();var compositeProgress=new WebInspector.CompositeProgress(this._progress);var subprogresses=[];for(var i=0; i<categories.length;++i) 103 var requests=WebInspector.networkLog.requests.slice();var compositeProgress=new WebInspector.CompositeProgress(this._progress);var subprogresses=[];for(var i=0; i<categories.length;++i)
104 subprogresses.push(compositeProgress.createSubProgress());for(var i=0;i<categori es.length;++i){var category=categories[i];var result=new WebInspector.AuditCateg oryResult(category);results.push(result);category.run(requests,ruleResultReadyCa llback.bind(this,result),categoryDoneCallback.bind(this),subprogresses[i]);}},_a uditFinishedCallback:function(launcherCallback,mainResourceURL,results) 104 subprogresses.push(compositeProgress.createSubProgress());for(var i=0;i<categori es.length;++i){var category=categories[i];var result=new WebInspector.AuditCateg oryResult(category);results.push(result);category.run(requests,ruleResultReadyCa llback.bind(this,result),categoryDoneCallback.bind(this),subprogresses[i]);}},_a uditFinishedCallback:function(launcherCallback,mainResourceURL,results)
105 {this._auditsPanel.auditFinishedCallback(mainResourceURL,results);if(!this._prog ress.isCanceled()) 105 {this._auditsPanel.auditFinishedCallback(mainResourceURL,results);if(!this._prog ress.isCanceled())
106 launcherCallback();},initiateAudit:function(categoryIds,progress,runImmediately, startedCallback,finishedCallback) 106 launcherCallback();},initiateAudit:function(categoryIds,progress,runImmediately, startedCallback,finishedCallback)
107 {if(!categoryIds||!categoryIds.length) 107 {if(!categoryIds||!categoryIds.length)
108 return;this._progress=progress;var categories=[];for(var i=0;i<categoryIds.lengt h;++i) 108 return;this._progress=progress;var categories=[];for(var i=0;i<categoryIds.lengt h;++i)
109 categories.push(this._auditsPanel.categoriesById[categoryIds[i]]);function start AuditWhenResourcesReady() 109 categories.push(this._auditsPanel.categoriesById[categoryIds[i]]);function start AuditWhenResourcesReady()
110 {startedCallback();this._executeAudit(categories,this._auditFinishedCallback.bin d(this,finishedCallback));} 110 {startedCallback();this._executeAudit(categories,this._auditFinishedCallback.bin d(this,finishedCallback));}
(...skipping 13 matching lines...) Expand all
124 a.target="_blank";return a;},resourceLink:function(url,line) 124 a.target="_blank";return a;},resourceLink:function(url,line)
125 {return WebInspector.linkifyResourceAsNode(url,line,"console-message-url webkit- html-resource-link");}};WebInspector.AuditFormatters.prototype={apply:function(v alue) 125 {return WebInspector.linkifyResourceAsNode(url,line,"console-message-url webkit- html-resource-link");}};WebInspector.AuditFormatters.prototype={apply:function(v alue)
126 {var formatter;var type=typeof value;var args;switch(type){case"string":case"boo lean":case"number":formatter=WebInspector.AuditFormatters.Registry.text;args=[va lue.toString()];break;case"object":if(value instanceof Node) 126 {var formatter;var type=typeof value;var args;switch(type){case"string":case"boo lean":case"number":formatter=WebInspector.AuditFormatters.Registry.text;args=[va lue.toString()];break;case"object":if(value instanceof Node)
127 return value;if(value instanceof Array){formatter=WebInspector.AuditFormatters.R egistry.concat;args=value;}else if(value.type&&value.arguments){formatter=WebIns pector.AuditFormatters.Registry[value.type];args=value.arguments;}} 127 return value;if(value instanceof Array){formatter=WebInspector.AuditFormatters.R egistry.concat;args=value;}else if(value.type&&value.arguments){formatter=WebIns pector.AuditFormatters.Registry[value.type];args=value.arguments;}}
128 if(!formatter) 128 if(!formatter)
129 throw"Invalid value or formatter: "+type+JSON.stringify(value);return formatter. apply(null,args);},partiallyApply:function(formatters,thisArgument,value) 129 throw"Invalid value or formatter: "+type+JSON.stringify(value);return formatter. apply(null,args);},partiallyApply:function(formatters,thisArgument,value)
130 {if(value instanceof Array) 130 {if(value instanceof Array)
131 return value.map(this.partiallyApply.bind(this,formatters,thisArgument));if(type of value==="object"&&typeof formatters[value.type]==="function"&&value.arguments ) 131 return value.map(this.partiallyApply.bind(this,formatters,thisArgument));if(type of value==="object"&&typeof formatters[value.type]==="function"&&value.arguments )
132 return formatters[value.type].apply(thisArgument,value.arguments);return value;} } 132 return formatters[value.type].apply(thisArgument,value.arguments);return value;} }
133 WebInspector.auditFormatters=new WebInspector.AuditFormatters();;WebInspector.Au ditLauncherView=function(auditController) 133 WebInspector.auditFormatters=new WebInspector.AuditFormatters();;WebInspector.Au ditLauncherView=function(auditController)
134 {WebInspector.View.call(this);this._auditController=auditController;this._catego ryIdPrefix="audit-category-item-";this._auditRunning=false;this.element.classLis t.add("audit-launcher-view");this.element.classList.add("panel-enabler-view");th is._contentElement=document.createElement("div");this._contentElement.className= "audit-launcher-view-content";this.element.appendChild(this._contentElement);thi s._boundCategoryClickListener=this._categoryClicked.bind(this);this._resetResour ceCount();this._sortedCategories=[];this._headerElement=document.createElement(" h1");this._headerElement.className="no-audits";this._headerElement.textContent=W ebInspector.UIString("No audits to run");this._contentElement.appendChild(this._ headerElement);WebInspector.networkManager.addEventListener(WebInspector.Network Manager.EventTypes.RequestStarted,this._onRequestStarted,this);WebInspector.netw orkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinish ed,this._onRequestFinished,this);var defaultSelectedAuditCategory={};defaultSele ctedAuditCategory[WebInspector.AuditLauncherView.AllCategoriesKey]=true;this._se lectedCategoriesSetting=WebInspector.settings.createSetting("selectedAuditCatego ries",defaultSelectedAuditCategory);} 134 {WebInspector.VBox.call(this);this.setMinimumSize(100,25);this._auditController= auditController;this._categoryIdPrefix="audit-category-item-";this._auditRunning =false;this.element.classList.add("audit-launcher-view");this.element.classList. add("panel-enabler-view");this._contentElement=document.createElement("div");thi s._contentElement.className="audit-launcher-view-content";this.element.appendChi ld(this._contentElement);this._boundCategoryClickListener=this._categoryClicked. bind(this);this._resetResourceCount();this._sortedCategories=[];this._headerElem ent=document.createElement("h1");this._headerElement.className="no-audits";this. _headerElement.textContent=WebInspector.UIString("No audits to run");this._conte ntElement.appendChild(this._headerElement);WebInspector.networkManager.addEventL istener(WebInspector.NetworkManager.EventTypes.RequestStarted,this._onRequestSta rted,this);WebInspector.networkManager.addEventListener(WebInspector.NetworkMana ger.EventTypes.RequestFinished,this._onRequestFinished,this);var defaultSelected AuditCategory={};defaultSelectedAuditCategory[WebInspector.AuditLauncherView.All CategoriesKey]=true;this._selectedCategoriesSetting=WebInspector.settings.create Setting("selectedAuditCategories",defaultSelectedAuditCategory);}
135 WebInspector.AuditLauncherView.AllCategoriesKey="__AllCategories";WebInspector.A uditLauncherView.prototype={_resetResourceCount:function() 135 WebInspector.AuditLauncherView.AllCategoriesKey="__AllCategories";WebInspector.A uditLauncherView.prototype={_resetResourceCount:function()
136 {this._loadedResources=0;this._totalResources=0;},_onRequestStarted:function(eve nt) 136 {this._loadedResources=0;this._totalResources=0;},_onRequestStarted:function(eve nt)
137 {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket ) 137 {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket )
138 return;++this._totalResources;this._updateResourceProgress();},_onRequestFinishe d:function(event) 138 return;++this._totalResources;this._updateResourceProgress();},_onRequestFinishe d:function(event)
139 {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket ) 139 {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket )
140 return;++this._loadedResources;this._updateResourceProgress();},addCategory:func tion(category) 140 return;++this._loadedResources;this._updateResourceProgress();},addCategory:func tion(category)
141 {if(!this._sortedCategories.length) 141 {if(!this._sortedCategories.length)
142 this._createLauncherUI();var selectedCategories=this._selectedCategoriesSetting. get();var categoryElement=this._createCategoryElement(category.displayName,categ ory.id);category._checkboxElement=categoryElement.firstChild;if(this._selectAllC heckboxElement.checked||selectedCategories[category.displayName]){category._chec kboxElement.checked=true;++this._currentCategoriesCount;} 142 this._createLauncherUI();var selectedCategories=this._selectedCategoriesSetting. get();var categoryElement=this._createCategoryElement(category.displayName,categ ory.id);category._checkboxElement=categoryElement.firstChild;if(this._selectAllC heckboxElement.checked||selectedCategories[category.displayName]){category._chec kboxElement.checked=true;++this._currentCategoriesCount;}
143 function compareCategories(a,b) 143 function compareCategories(a,b)
144 {var aTitle=a.displayName||"";var bTitle=b.displayName||"";return aTitle.localeC ompare(bTitle);} 144 {var aTitle=a.displayName||"";var bTitle=b.displayName||"";return aTitle.localeC ompare(bTitle);}
(...skipping 17 matching lines...) Expand all
162 {var labelElement=document.createElement("label");labelElement.id=this._category IdPrefix+id;var element=document.createElement("input");element.type="checkbox"; if(id!=="") 162 {var labelElement=document.createElement("label");labelElement.id=this._category IdPrefix+id;var element=document.createElement("input");element.type="checkbox"; if(id!=="")
163 element.addEventListener("click",this._boundCategoryClickListener,false);labelEl ement.appendChild(element);labelElement.appendChild(document.createTextNode(titl e));labelElement.__displayName=title;return labelElement;},_createLauncherUI:fun ction() 163 element.addEventListener("click",this._boundCategoryClickListener,false);labelEl ement.appendChild(element);labelElement.appendChild(document.createTextNode(titl e));labelElement.__displayName=title;return labelElement;},_createLauncherUI:fun ction()
164 {this._headerElement=document.createElement("h1");this._headerElement.textConten t=WebInspector.UIString("Select audits to run");for(var child=0;child<this._cont entElement.children.length;++child) 164 {this._headerElement=document.createElement("h1");this._headerElement.textConten t=WebInspector.UIString("Select audits to run");for(var child=0;child<this._cont entElement.children.length;++child)
165 this._contentElement.removeChild(this._contentElement.children[child]);this._con tentElement.appendChild(this._headerElement);function handleSelectAllClick(event ) 165 this._contentElement.removeChild(this._contentElement.children[child]);this._con tentElement.appendChild(this._headerElement);function handleSelectAllClick(event )
166 {this._selectAllClicked(event.target.checked,true);} 166 {this._selectAllClicked(event.target.checked,true);}
167 var categoryElement=this._createCategoryElement(WebInspector.UIString("Select Al l"),"");categoryElement.id="audit-launcher-selectall";this._selectAllCheckboxEle ment=categoryElement.firstChild;this._selectAllCheckboxElement.checked=this._sel ectedCategoriesSetting.get()[WebInspector.AuditLauncherView.AllCategoriesKey];th is._selectAllCheckboxElement.addEventListener("click",handleSelectAllClick.bind( this),false);this._contentElement.appendChild(categoryElement);this._categoriesE lement=this._contentElement.createChild("fieldset","audit-categories-container") ;this._currentCategoriesCount=0;this._contentElement.createChild("div","flexible -space");this._buttonContainerElement=this._contentElement.createChild("div","bu tton-container");var labelElement=this._buttonContainerElement.createChild("labe l");this._auditPresentStateElement=labelElement.createChild("input");this._audit PresentStateElement.name="audit-mode";this._auditPresentStateElement.type="radio ";this._auditPresentStateElement.checked=true;this._auditPresentStateLabelElemen t=document.createTextNode(WebInspector.UIString("Audit Present State"));labelEle ment.appendChild(this._auditPresentStateLabelElement);labelElement=this._buttonC ontainerElement.createChild("label");this._auditReloadedStateElement=labelElemen t.createChild("input");this._auditReloadedStateElement.name="audit-mode";this._a uditReloadedStateElement.type="radio";labelElement.appendChild(document.createTe xtNode("Reload Page and Audit on Load"));this._launchButton=this._buttonContaine rElement.createChild("button");this._launchButton.textContent=WebInspector.UIStr ing("Run");this._launchButton.addEventListener("click",this._launchButtonClicked .bind(this),false);this._clearButton=this._buttonContainerElement.createChild("b utton");this._clearButton.textContent=WebInspector.UIString("Clear");this._clear Button.addEventListener("click",this._clearButtonClicked.bind(this),false);this. _selectAllClicked(this._selectAllCheckboxElement.checked);},_updateResourceProgr ess:function() 167 var categoryElement=this._createCategoryElement(WebInspector.UIString("Select Al l"),"");categoryElement.id="audit-launcher-selectall";this._selectAllCheckboxEle ment=categoryElement.firstChild;this._selectAllCheckboxElement.checked=this._sel ectedCategoriesSetting.get()[WebInspector.AuditLauncherView.AllCategoriesKey];th is._selectAllCheckboxElement.addEventListener("click",handleSelectAllClick.bind( this),false);this._contentElement.appendChild(categoryElement);this._categoriesE lement=this._contentElement.createChild("fieldset","audit-categories-container") ;this._currentCategoriesCount=0;this._contentElement.createChild("div","flexible -space");this._buttonContainerElement=this._contentElement.createChild("div","bu tton-container");var labelElement=this._buttonContainerElement.createChild("labe l");this._auditPresentStateElement=labelElement.createChild("input");this._audit PresentStateElement.name="audit-mode";this._auditPresentStateElement.type="radio ";this._auditPresentStateElement.checked=true;this._auditPresentStateLabelElemen t=document.createTextNode(WebInspector.UIString("Audit Present State"));labelEle ment.appendChild(this._auditPresentStateLabelElement);labelElement=this._buttonC ontainerElement.createChild("label");this._auditReloadedStateElement=labelElemen t.createChild("input");this._auditReloadedStateElement.name="audit-mode";this._a uditReloadedStateElement.type="radio";labelElement.appendChild(document.createTe xtNode("Reload Page and Audit on Load"));this._launchButton=this._buttonContaine rElement.createChild("button");this._launchButton.textContent=WebInspector.UIStr ing("Run");this._launchButton.addEventListener("click",this._launchButtonClicked .bind(this),false);this._clearButton=this._buttonContainerElement.createChild("b utton");this._clearButton.textContent=WebInspector.UIString("Clear");this._clear Button.addEventListener("click",this._clearButtonClicked.bind(this),false);this. _selectAllClicked(this._selectAllCheckboxElement.checked);},_updateResourceProgr ess:function()
168 {if(this._displayResourceLoadingProgress) 168 {if(this._displayResourceLoadingProgress)
169 this._progressIndicator.setTitle(WebInspector.UIString("Loading (%d of %d)",this ._loadedResources,this._totalResources));},_selectedCategoriesUpdated:function(u serGesture) 169 this._progressIndicator.setTitle(WebInspector.UIString("Loading (%d of %d)",this ._loadedResources,this._totalResources));},_selectedCategoriesUpdated:function(u serGesture)
170 {var selectedCategories=userGesture?{}:this._selectedCategoriesSetting.get();var childNodes=this._categoriesElement.childNodes;for(var i=0,length=childNodes.len gth;i<length;++i) 170 {var selectedCategories=userGesture?{}:this._selectedCategoriesSetting.get();var childNodes=this._categoriesElement.childNodes;for(var i=0,length=childNodes.len gth;i<length;++i)
171 selectedCategories[childNodes[i].__displayName]=childNodes[i].firstChild.checked ;selectedCategories[WebInspector.AuditLauncherView.AllCategoriesKey]=this._selec tAllCheckboxElement.checked;this._selectedCategoriesSetting.set(selectedCategori es);this._updateButton();},_updateButton:function() 171 selectedCategories[childNodes[i].__displayName]=childNodes[i].firstChild.checked ;selectedCategories[WebInspector.AuditLauncherView.AllCategoriesKey]=this._selec tAllCheckboxElement.checked;this._selectedCategoriesSetting.set(selectedCategori es);this._updateButton();},_updateButton:function()
172 {this._launchButton.textContent=this._auditRunning?WebInspector.UIString("Stop") :WebInspector.UIString("Run");this._launchButton.disabled=!this._currentCategori esCount;},__proto__:WebInspector.View.prototype};WebInspector.AuditResultView=fu nction(categoryResults) 172 {this._launchButton.textContent=this._auditRunning?WebInspector.UIString("Stop") :WebInspector.UIString("Run");this._launchButton.disabled=!this._currentCategori esCount;},__proto__:WebInspector.VBox.prototype};WebInspector.AuditResultView=fu nction(categoryResults)
173 {WebInspector.SidebarPaneStack.call(this);this.element.classList.add("audit-resu lt-view");function categorySorter(a,b){return(a.title||"").localeCompare(b.title ||"");} 173 {WebInspector.SidebarPaneStack.call(this);this.setMinimumSize(100,25);this.eleme nt.classList.add("audit-result-view","fill");function categorySorter(a,b){return (a.title||"").localeCompare(b.title||"");}
174 categoryResults.sort(categorySorter);for(var i=0;i<categoryResults.length;++i) 174 categoryResults.sort(categorySorter);for(var i=0;i<categoryResults.length;++i)
175 this.addPane(new WebInspector.AuditCategoryResultPane(categoryResults[i]));} 175 this.addPane(new WebInspector.AuditCategoryResultPane(categoryResults[i]));}
176 WebInspector.AuditResultView.prototype={__proto__:WebInspector.SidebarPaneStack. prototype} 176 WebInspector.AuditResultView.prototype={__proto__:WebInspector.SidebarPaneStack. prototype}
177 WebInspector.AuditCategoryResultPane=function(categoryResult) 177 WebInspector.AuditCategoryResultPane=function(categoryResult)
178 {WebInspector.SidebarPane.call(this,categoryResult.title);var treeOutlineElement =document.createElement("ol");this.bodyElement.classList.add("audit-result-tree" );this.bodyElement.appendChild(treeOutlineElement);this._treeOutline=new TreeOut line(treeOutlineElement);this._treeOutline.expandTreeElementsWhenArrowing=true;f unction ruleSorter(a,b) 178 {WebInspector.SidebarPane.call(this,categoryResult.title);var treeOutlineElement =document.createElement("ol");this.bodyElement.classList.add("audit-result-tree" );this.bodyElement.appendChild(treeOutlineElement);this._treeOutline=new TreeOut line(treeOutlineElement);this._treeOutline.expandTreeElementsWhenArrowing=true;f unction ruleSorter(a,b)
179 {var result=WebInspector.AuditRule.SeverityOrder[a.severity||0]-WebInspector.Aud itRule.SeverityOrder[b.severity||0];if(!result) 179 {var result=WebInspector.AuditRule.SeverityOrder[a.severity||0]-WebInspector.Aud itRule.SeverityOrder[b.severity||0];if(!result)
180 result=(a.value||"").localeCompare(b.value||"");return result;} 180 result=(a.value||"").localeCompare(b.value||"");return result;}
181 categoryResult.ruleResults.sort(ruleSorter);for(var i=0;i<categoryResult.ruleRes ults.length;++i){var ruleResult=categoryResult.ruleResults[i];var treeElement=th is._appendResult(this._treeOutline,ruleResult);treeElement.listItemElement.class List.add("audit-result");if(ruleResult.severity){var severityElement=document.cr eateElement("div");severityElement.className="severity-"+ruleResult.severity;tre eElement.listItemElement.appendChild(severityElement);}} 181 categoryResult.ruleResults.sort(ruleSorter);for(var i=0;i<categoryResult.ruleRes ults.length;++i){var ruleResult=categoryResult.ruleResults[i];var treeElement=th is._appendResult(this._treeOutline,ruleResult,ruleResult.severity);treeElement.l istItemElement.classList.add("audit-result");}
182 this.expand();} 182 this.expand();}
183 WebInspector.AuditCategoryResultPane.prototype={_appendResult:function(parentTre eElement,result) 183 WebInspector.AuditCategoryResultPane.prototype={_appendResult:function(parentTre eElement,result,severity)
184 {var title="";if(typeof result.value==="string"){title=result.value;if(result.vi olationCount) 184 {var title="";if(typeof result.value==="string"){title=result.value;if(result.vi olationCount)
185 title=String.sprintf("%s (%d)",title,result.violationCount);} 185 title=String.sprintf("%s (%d)",title,result.violationCount);}
186 var treeElement=new TreeElement(title,null,!!result.children);parentTreeElement. appendChild(treeElement);if(result.className) 186 var titleFragment=document.createDocumentFragment();if(severity){var severityEle ment=document.createElement("div");severityElement.className="severity-"+severit y;titleFragment.appendChild(severityElement);}
187 titleFragment.appendChild(document.createTextNode(title));var treeElement=new Tr eeElement(titleFragment,null,!!result.children);parentTreeElement.appendChild(tr eeElement);if(result.className)
187 treeElement.listItemElement.classList.add(result.className);if(typeof result.val ue!=="string") 188 treeElement.listItemElement.classList.add(result.className);if(typeof result.val ue!=="string")
188 treeElement.listItemElement.appendChild(WebInspector.auditFormatters.apply(resul t.value));if(result.children){for(var i=0;i<result.children.length;++i) 189 treeElement.listItemElement.appendChild(WebInspector.auditFormatters.apply(resul t.value));if(result.children){for(var i=0;i<result.children.length;++i)
189 this._appendResult(treeElement,result.children[i]);} 190 this._appendResult(treeElement,result.children[i]);}
190 if(result.expanded){treeElement.listItemElement.classList.remove("parent");treeE lement.listItemElement.classList.add("parent-expanded");treeElement.expand();} 191 if(result.expanded){treeElement.listItemElement.classList.remove("parent");treeE lement.listItemElement.classList.add("parent-expanded");treeElement.expand();}
191 return treeElement;},__proto__:WebInspector.SidebarPane.prototype};WebInspector. AuditRules.IPAddressRegexp=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;WebInspector.A uditRules.CacheableResponseCodes={200:true,203:true,206:true,300:true,301:true,4 10:true,304:true} 192 return treeElement;},__proto__:WebInspector.SidebarPane.prototype};WebInspector. AuditRules.IPAddressRegexp=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;WebInspector.A uditRules.CacheableResponseCodes={200:true,203:true,206:true,300:true,301:true,4 10:true,304:true}
192 WebInspector.AuditRules.getDomainToResourcesMap=function(requests,types,needFull Resources) 193 WebInspector.AuditRules.getDomainToResourcesMap=function(requests,types,needFull Resources)
193 {var domainToResourcesMap={};for(var i=0,size=requests.length;i<size;++i){var re quest=requests[i];if(types&&types.indexOf(request.type)===-1) 194 {var domainToResourcesMap={};for(var i=0,size=requests.length;i<size;++i){var re quest=requests[i];if(types&&types.indexOf(request.type)===-1)
194 continue;var parsedURL=request.url.asParsedURL();if(!parsedURL) 195 continue;var parsedURL=request.url.asParsedURL();if(!parsedURL)
195 continue;var domain=parsedURL.host;var domainResources=domainToResourcesMap[doma in];if(domainResources===undefined){domainResources=[];domainToResourcesMap[doma in]=domainResources;} 196 continue;var domain=parsedURL.host;var domainResources=domainToResourcesMap[doma in];if(domainResources===undefined){domainResources=[];domainToResourcesMap[doma in]=domainResources;}
196 domainResources.push(needFullResources?request:request.url);} 197 domainResources.push(needFullResources?request:request.url);}
(...skipping 25 matching lines...) Expand all
222 {var summary=result.addChild("");var domainToResourcesMap=WebInspector.AuditRule s.getDomainToResourcesMap(requests,null,false);for(var domain in domainToResourc esMap){if(domainToResourcesMap[domain].length>1) 223 {var summary=result.addChild("");var domainToResourcesMap=WebInspector.AuditRule s.getDomainToResourcesMap(requests,null,false);for(var domain in domainToResourc esMap){if(domainToResourcesMap[domain].length>1)
223 continue;var parsedURL=domain.asParsedURL();if(!parsedURL) 224 continue;var parsedURL=domain.asParsedURL();if(!parsedURL)
224 continue;if(!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp)) 225 continue;if(!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp))
225 continue;summary.addSnippet(domain);result.violationCount++;} 226 continue;summary.addSnippet(domain);result.violationCount++;}
226 if(!summary.children||summary.children.length<=this._hostCountThreshold){callbac k(null);return;} 227 if(!summary.children||summary.children.length<=this._hostCountThreshold){callbac k(null);return;}
227 summary.value=WebInspector.UIString("The following domains only serve one resour ce each. If possible, avoid the extra DNS lookups by serving these resources fro m existing domains.");callback(result);},__proto__:WebInspector.AuditRule.protot ype} 228 summary.value=WebInspector.UIString("The following domains only serve one resour ce each. If possible, avoid the extra DNS lookups by serving these resources fro m existing domains.");callback(result);},__proto__:WebInspector.AuditRule.protot ype}
228 WebInspector.AuditRules.ParallelizeDownloadRule=function(optimalHostnameCount,mi nRequestThreshold,minBalanceThreshold) 229 WebInspector.AuditRules.ParallelizeDownloadRule=function(optimalHostnameCount,mi nRequestThreshold,minBalanceThreshold)
229 {WebInspector.AuditRule.call(this,"network-parallelizehosts",WebInspector.UIStri ng("Parallelize downloads across hostnames"));this._optimalHostnameCount=optimal HostnameCount;this._minRequestThreshold=minRequestThreshold;this._minBalanceThre shold=minBalanceThreshold;} 230 {WebInspector.AuditRule.call(this,"network-parallelizehosts",WebInspector.UIStri ng("Parallelize downloads across hostnames"));this._optimalHostnameCount=optimal HostnameCount;this._minRequestThreshold=minRequestThreshold;this._minBalanceThre shold=minBalanceThreshold;}
230 WebInspector.AuditRules.ParallelizeDownloadRule.prototype={doRun:function(reques ts,result,callback,progress) 231 WebInspector.AuditRules.ParallelizeDownloadRule.prototype={doRun:function(reques ts,result,callback,progress)
231 {function hostSorter(a,b) 232 {function hostSorter(a,b)
232 {var aCount=domainToResourcesMap[a].length;var bCount=domainToResourcesMap[b].le ngth;return(aCount<bCount)?1:(aCount==bCount)?0:-1;} 233 {var aCount=domainToResourcesMap[a].length;var bCount=domainToResourcesMap[b].le ngth;return(aCount<bCount)?1:(aCount===bCount)?0:-1;}
233 var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(request s,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true) ;var hosts=[];for(var url in domainToResourcesMap) 234 var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(request s,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true) ;var hosts=[];for(var url in domainToResourcesMap)
234 hosts.push(url);if(!hosts.length){callback(null);return;} 235 hosts.push(url);if(!hosts.length){callback(null);return;}
235 hosts.sort(hostSorter);var optimalHostnameCount=this._optimalHostnameCount;if(ho sts.length>optimalHostnameCount) 236 hosts.sort(hostSorter);var optimalHostnameCount=this._optimalHostnameCount;if(ho sts.length>optimalHostnameCount)
236 hosts.splice(optimalHostnameCount);var busiestHostResourceCount=domainToResource sMap[hosts[0]].length;var requestCountAboveThreshold=busiestHostResourceCount-th is._minRequestThreshold;if(requestCountAboveThreshold<=0){callback(null);return; } 237 hosts.splice(optimalHostnameCount);var busiestHostResourceCount=domainToResource sMap[hosts[0]].length;var requestCountAboveThreshold=busiestHostResourceCount-th is._minRequestThreshold;if(requestCountAboveThreshold<=0){callback(null);return; }
237 var avgResourcesPerHost=0;for(var i=0,size=hosts.length;i<size;++i) 238 var avgResourcesPerHost=0;for(var i=0,size=hosts.length;i<size;++i)
238 avgResourcesPerHost+=domainToResourcesMap[hosts[i]].length;avgResourcesPerHost/= optimalHostnameCount;avgResourcesPerHost=Math.max(avgResourcesPerHost,1);var pct AboveAvg=(requestCountAboveThreshold/avgResourcesPerHost)-1.0;var minBalanceThre shold=this._minBalanceThreshold;if(pctAboveAvg<minBalanceThreshold){callback(nul l);return;} 239 avgResourcesPerHost+=domainToResourcesMap[hosts[i]].length;avgResourcesPerHost/= optimalHostnameCount;avgResourcesPerHost=Math.max(avgResourcesPerHost,1);var pct AboveAvg=(requestCountAboveThreshold/avgResourcesPerHost)-1.0;var minBalanceThre shold=this._minBalanceThreshold;if(pctAboveAvg<minBalanceThreshold){callback(nul l);return;}
239 var requestsOnBusiestHost=domainToResourcesMap[hosts[0]];var entry=result.addChi ld(WebInspector.UIString("This page makes %d parallelizable requests to %s. Incr ease download parallelization by distributing the following requests across mult iple hostnames.",busiestHostResourceCount,hosts[0]),true);for(var i=0;i<requests OnBusiestHost.length;++i) 240 var requestsOnBusiestHost=domainToResourcesMap[hosts[0]];var entry=result.addChi ld(WebInspector.UIString("This page makes %d parallelizable requests to %s. Incr ease download parallelization by distributing the following requests across mult iple hostnames.",busiestHostResourceCount,hosts[0]),true);for(var i=0;i<requests OnBusiestHost.length;++i)
240 entry.addURL(requestsOnBusiestHost[i].url);result.violationCount=requestsOnBusie stHost.length;callback(result);},__proto__:WebInspector.AuditRule.prototype} 241 entry.addURL(requestsOnBusiestHost[i].url);result.violationCount=requestsOnBusie stHost.length;callback(result);},__proto__:WebInspector.AuditRule.prototype}
241 WebInspector.AuditRules.UnusedCssRule=function() 242 WebInspector.AuditRules.UnusedCssRule=function()
242 {WebInspector.AuditRule.call(this,"page-unusedcss",WebInspector.UIString("Remove unused CSS rules"));} 243 {WebInspector.AuditRule.call(this,"page-unusedcss",WebInspector.UIString("Remove unused CSS rules"));}
243 WebInspector.AuditRules.UnusedCssRule.prototype={doRun:function(requests,result, callback,progress) 244 WebInspector.AuditRules.UnusedCssRule.prototype={doRun:function(requests,result, callback,progress)
244 {var self=this;function evalCallback(styleSheets){if(progress.isCanceled()) 245 {function evalCallback(styleSheets){if(!styleSheets.length)
245 return;if(!styleSheets.length)
246 return callback(null);var selectors=[];var testedSelectors={};for(var i=0;i<styl eSheets.length;++i){var styleSheet=styleSheets[i];for(var curRule=0;curRule<styl eSheet.rules.length;++curRule){var selectorText=styleSheet.rules[curRule].select orText;if(testedSelectors[selectorText]) 246 return callback(null);var selectors=[];var testedSelectors={};for(var i=0;i<styl eSheets.length;++i){var styleSheet=styleSheets[i];for(var curRule=0;curRule<styl eSheet.rules.length;++curRule){var selectorText=styleSheet.rules[curRule].select orText;if(testedSelectors[selectorText])
247 continue;selectors.push(selectorText);testedSelectors[selectorText]=1;}} 247 continue;selectors.push(selectorText);testedSelectors[selectorText]=1;}}
248 var foundSelectors={};function selectorsCallback(styleSheets) 248 var foundSelectors={};function selectorsCallback(styleSheets)
249 {if(progress.isCanceled()) 249 {if(progress.isCanceled())
250 return;var inlineBlockOrdinal=0;var totalStylesheetSize=0;var totalUnusedStylesh eetSize=0;var summary;for(var i=0;i<styleSheets.length;++i){var styleSheet=style Sheets[i];var unusedRules=[];for(var curRule=0;curRule<styleSheet.rules.length;+ +curRule){var rule=styleSheet.rules[curRule];if(!testedSelectors[rule.selectorTe xt]||foundSelectors[rule.selectorText]) 250 return;var inlineBlockOrdinal=0;var totalStylesheetSize=0;var totalUnusedStylesh eetSize=0;var summary;for(var i=0;i<styleSheets.length;++i){var styleSheet=style Sheets[i];var unusedRules=[];for(var curRule=0;curRule<styleSheet.rules.length;+ +curRule){var rule=styleSheet.rules[curRule];if(!testedSelectors[rule.selectorTe xt]||foundSelectors[rule.selectorText])
251 continue;unusedRules.push(rule.selectorText);} 251 continue;unusedRules.push(rule.selectorText);}
252 totalStylesheetSize+=styleSheet.rules.length;totalUnusedStylesheetSize+=unusedRu les.length;if(!unusedRules.length) 252 totalStylesheetSize+=styleSheet.rules.length;totalUnusedStylesheetSize+=unusedRu les.length;if(!unusedRules.length)
253 continue;var resource=WebInspector.resourceForURL(styleSheet.sourceURL);var isIn lineBlock=resource&&resource.request&&resource.request.type==WebInspector.resour ceTypes.Document;var url=!isInlineBlock?WebInspector.AuditRuleResult.linkifyDisp layName(styleSheet.sourceURL):WebInspector.UIString("Inline block #%d",++inlineB lockOrdinal);var pctUnused=Math.round(100*unusedRules.length/styleSheet.rules.le ngth);if(!summary) 253 continue;var resource=WebInspector.resourceForURL(styleSheet.sourceURL);var isIn lineBlock=resource&&resource.request&&resource.request.type===WebInspector.resou rceTypes.Document;var url=!isInlineBlock?WebInspector.AuditRuleResult.linkifyDis playName(styleSheet.sourceURL):WebInspector.UIString("Inline block #%d",++inline BlockOrdinal);var pctUnused=Math.round(100*unusedRules.length/styleSheet.rules.l ength);if(!summary)
254 summary=result.addChild("",true);var entry=summary.addFormatted("%s: %d% is not used by the current page.",url,pctUnused);for(var j=0;j<unusedRules.length;++j) 254 summary=result.addChild("",true);var entry=summary.addFormatted("%s: %d% is not used by the current page.",url,pctUnused);for(var j=0;j<unusedRules.length;++j)
255 entry.addSnippet(unusedRules[j]);result.violationCount+=unusedRules.length;} 255 entry.addSnippet(unusedRules[j]);result.violationCount+=unusedRules.length;}
256 if(!totalUnusedStylesheetSize) 256 if(!totalUnusedStylesheetSize)
257 return callback(null);var totalUnusedPercent=Math.round(100*totalUnusedStyleshee tSize/totalStylesheetSize);summary.value=WebInspector.UIString("%s rules (%d%) o f CSS not used by the current page.",totalUnusedStylesheetSize,totalUnusedPercen t);callback(result);} 257 return callback(null);var totalUnusedPercent=Math.round(100*totalUnusedStyleshee tSize/totalStylesheetSize);summary.value=WebInspector.UIString("%s rules (%d%) o f CSS not used by the current page.",totalUnusedStylesheetSize,totalUnusedPercen t);callback(result);}
258 function queryCallback(boundSelectorsCallback,selector,nodeId) 258 function queryCallback(boundSelectorsCallback,selector,nodeId)
259 {if(nodeId) 259 {if(nodeId)
260 foundSelectors[selector]=true;if(boundSelectorsCallback) 260 foundSelectors[selector]=true;if(boundSelectorsCallback)
261 boundSelectorsCallback();} 261 boundSelectorsCallback();}
262 function documentLoaded(selectors,document){var pseudoSelectorRegexp=/::?(?:[\w- ]+)(?:\(.*?\))?/g;if(!selectors.length){selectorsCallback([]);return;} 262 function documentLoaded(selectors,document){var pseudoSelectorRegexp=/::?(?:[\w- ]+)(?:\(.*?\))?/g;if(!selectors.length){selectorsCallback([]);return;}
263 for(var i=0;i<selectors.length;++i){if(progress.isCanceled()) 263 for(var i=0;i<selectors.length;++i){if(progress.isCanceled())
264 return;var effectiveSelector=selectors[i].replace(pseudoSelectorRegexp,"");WebIn spector.domAgent.querySelector(document.id,effectiveSelector,queryCallback.bind( null,i===selectors.length-1?selectorsCallback.bind(null,styleSheets):null,select ors[i]));}} 264 return;var effectiveSelector=selectors[i].replace(pseudoSelectorRegexp,"");WebIn spector.domModel.querySelector(document.id,effectiveSelector,queryCallback.bind( null,i===selectors.length-1?selectorsCallback.bind(null,styleSheets):null,select ors[i]));}}
265 WebInspector.domAgent.requestDocument(documentLoaded.bind(null,selectors));} 265 WebInspector.domModel.requestDocument(documentLoaded.bind(null,selectors));}
266 function styleSheetCallback(styleSheets,sourceURL,continuation,styleSheet) 266 var styleSheetInfos=WebInspector.cssModel.allStyleSheets();if(!styleSheetInfos|| !styleSheetInfos.length){evalCallback([]);return;}
267 {if(progress.isCanceled()) 267 var styleSheetProcessor=new WebInspector.AuditRules.StyleSheetProcessor(styleShe etInfos,progress,evalCallback);styleSheetProcessor.run();},__proto__:WebInspecto r.AuditRule.prototype}
268 return;if(styleSheet){styleSheet.sourceURL=sourceURL;styleSheets.push(styleSheet );} 268 WebInspector.AuditRules.ParsedStyleSheet;WebInspector.AuditRules.StyleSheetProce ssor=function(styleSheetHeaders,progress,styleSheetsParsedCallback)
269 if(continuation) 269 {this._styleSheetHeaders=styleSheetHeaders;this._progress=progress;this._styleSh eets=[];this._styleSheetsParsedCallback=styleSheetsParsedCallback;}
270 continuation(styleSheets);} 270 WebInspector.AuditRules.StyleSheetProcessor.prototype={run:function()
271 function allStylesCallback(error,styleSheetInfos) 271 {this._parser=new WebInspector.CSSParser();this._processNextStyleSheet();},_term inateWorker:function()
272 {if(progress.isCanceled()) 272 {if(this._parser){this._parser.dispose();delete this._parser;}},_finish:function ()
273 return;if(error||!styleSheetInfos||!styleSheetInfos.length) 273 {this._terminateWorker();this._styleSheetsParsedCallback(this._styleSheets);},_p rocessNextStyleSheet:function()
274 return evalCallback([]);var styleSheets=[];for(var i=0;i<styleSheetInfos.length; ++i){var info=styleSheetInfos[i];WebInspector.CSSStyleSheet.createForId(info.sty leSheetId,styleSheetCallback.bind(null,styleSheets,info.sourceURL,i==styleSheetI nfos.length-1?evalCallback:null));}} 274 {if(!this._styleSheetHeaders.length){this._finish();return;}
275 CSSAgent.getAllStyleSheets(allStylesCallback);},__proto__:WebInspector.AuditRule .prototype} 275 this._currentStyleSheetHeader=this._styleSheetHeaders.shift();this._parser.fetch AndParse(this._currentStyleSheetHeader,this._onStyleSheetParsed.bind(this));},_o nStyleSheetParsed:function(rules)
276 {if(this._progress.isCanceled()){this._terminateWorker();return;}
277 var styleRules=[];for(var i=0;i<rules.length;++i){var rule=rules[i];if(rule.sele ctorText)
278 styleRules.push(rule);}
279 this._styleSheets.push({sourceURL:this._currentStyleSheetHeader.sourceURL,rules: styleRules});this._processNextStyleSheet();},}
276 WebInspector.AuditRules.CacheControlRule=function(id,name) 280 WebInspector.AuditRules.CacheControlRule=function(id,name)
277 {WebInspector.AuditRule.call(this,id,name);} 281 {WebInspector.AuditRule.call(this,id,name);}
278 WebInspector.AuditRules.CacheControlRule.MillisPerMonth=1000*60*60*24*30;WebInsp ector.AuditRules.CacheControlRule.prototype={doRun:function(requests,result,call back,progress) 282 WebInspector.AuditRules.CacheControlRule.MillisPerMonth=1000*60*60*24*30;WebInsp ector.AuditRules.CacheControlRule.prototype={doRun:function(requests,result,call back,progress)
279 {var cacheableAndNonCacheableResources=this._cacheableAndNonCacheableResources(r equests);if(cacheableAndNonCacheableResources[0].length) 283 {var cacheableAndNonCacheableResources=this._cacheableAndNonCacheableResources(r equests);if(cacheableAndNonCacheableResources[0].length)
280 this.runChecks(cacheableAndNonCacheableResources[0],result);this.handleNonCachea bleResources(cacheableAndNonCacheableResources[1],result);callback(result);},han dleNonCacheableResources:function(requests,result) 284 this.runChecks(cacheableAndNonCacheableResources[0],result);this.handleNonCachea bleResources(cacheableAndNonCacheableResources[1],result);callback(result);},han dleNonCacheableResources:function(requests,result)
281 {},_cacheableAndNonCacheableResources:function(requests) 285 {},_cacheableAndNonCacheableResources:function(requests)
282 {var processedResources=[[],[]];for(var i=0;i<requests.length;++i){var request=r equests[i];if(!this.isCacheableResource(request)) 286 {var processedResources=[[],[]];for(var i=0;i<requests.length;++i){var request=r equests[i];if(!this.isCacheableResource(request))
283 continue;if(this._isExplicitlyNonCacheable(request)) 287 continue;if(this._isExplicitlyNonCacheable(request))
284 processedResources[1].push(request);else 288 processedResources[1].push(request);else
285 processedResources[0].push(request);} 289 processedResources[0].push(request);}
286 return processedResources;},execCheck:function(messageText,requestCheckFunction, requests,result) 290 return processedResources;},execCheck:function(messageText,requestCheckFunction, requests,result)
287 {var requestCount=requests.length;var urls=[];for(var i=0;i<requestCount;++i){if (requestCheckFunction.call(this,requests[i])) 291 {var requestCount=requests.length;var urls=[];for(var i=0;i<requestCount;++i){if (requestCheckFunction.call(this,requests[i]))
288 urls.push(requests[i].url);} 292 urls.push(requests[i].url);}
289 if(urls.length){var entry=result.addChild(messageText,true);entry.addURLs(urls); result.violationCount+=urls.length;}},freshnessLifetimeGreaterThan:function(requ est,timeMs) 293 if(urls.length){var entry=result.addChild(messageText,true);entry.addURLs(urls); result.violationCount+=urls.length;}},freshnessLifetimeGreaterThan:function(requ est,timeMs)
290 {var dateHeader=this.responseHeader(request,"Date");if(!dateHeader) 294 {var dateHeader=this.responseHeader(request,"Date");if(!dateHeader)
291 return false;var dateHeaderMs=Date.parse(dateHeader);if(isNaN(dateHeaderMs)) 295 return false;var dateHeaderMs=Date.parse(dateHeader);if(isNaN(dateHeaderMs))
292 return false;var freshnessLifetimeMs;var maxAgeMatch=this.responseHeaderMatch(re quest,"Cache-Control","max-age=(\\d+)");if(maxAgeMatch) 296 return false;var freshnessLifetimeMs;var maxAgeMatch=this.responseHeaderMatch(re quest,"Cache-Control","max-age=(\\d+)");if(maxAgeMatch)
293 freshnessLifetimeMs=(maxAgeMatch[1])?1000*maxAgeMatch[1]:0;else{var expiresHeade r=this.responseHeader(request,"Expires");if(expiresHeader){var expDate=Date.pars e(expiresHeader);if(!isNaN(expDate)) 297 freshnessLifetimeMs=(maxAgeMatch[1])?1000*maxAgeMatch[1]:0;else{var expiresHeade r=this.responseHeader(request,"Expires");if(expiresHeader){var expDate=Date.pars e(expiresHeader);if(!isNaN(expDate))
294 freshnessLifetimeMs=expDate-dateHeaderMs;}} 298 freshnessLifetimeMs=expDate-dateHeaderMs;}}
295 return(isNaN(freshnessLifetimeMs))?false:freshnessLifetimeMs>timeMs;},responseHe ader:function(request,header) 299 return(isNaN(freshnessLifetimeMs))?false:freshnessLifetimeMs>timeMs;},responseHe ader:function(request,header)
296 {return request.responseHeaderValue(header);},hasResponseHeader:function(request ,header) 300 {return request.responseHeaderValue(header);},hasResponseHeader:function(request ,header)
297 {return request.responseHeaderValue(header)!==undefined;},isCompressible:functio n(request) 301 {return request.responseHeaderValue(header)!==undefined;},isCompressible:functio n(request)
298 {return request.type.isTextType();},isPubliclyCacheable:function(request) 302 {return request.type.isTextType();},isPubliclyCacheable:function(request)
299 {if(this._isExplicitlyNonCacheable(request)) 303 {if(this._isExplicitlyNonCacheable(request))
300 return false;if(this.responseHeaderMatch(request,"Cache-Control","public")) 304 return false;if(this.responseHeaderMatch(request,"Cache-Control","public"))
301 return true;return request.url.indexOf("?")==-1&&!this.responseHeaderMatch(reque st,"Cache-Control","private");},responseHeaderMatch:function(request,header,rege xp) 305 return true;return request.url.indexOf("?")===-1&&!this.responseHeaderMatch(requ est,"Cache-Control","private");},responseHeaderMatch:function(request,header,reg exp)
302 {return request.responseHeaderValue(header)?request.responseHeaderValue(header). match(new RegExp(regexp,"im")):null;},hasExplicitExpiration:function(request) 306 {return request.responseHeaderValue(header)?request.responseHeaderValue(header). match(new RegExp(regexp,"im")):null;},hasExplicitExpiration:function(request)
303 {return this.hasResponseHeader(request,"Date")&&(this.hasResponseHeader(request, "Expires")||!!this.responseHeaderMatch(request,"Cache-Control","max-age"));},_is ExplicitlyNonCacheable:function(request) 307 {return this.hasResponseHeader(request,"Date")&&(this.hasResponseHeader(request, "Expires")||!!this.responseHeaderMatch(request,"Cache-Control","max-age"));},_is ExplicitlyNonCacheable:function(request)
304 {var hasExplicitExp=this.hasExplicitExpiration(request);return!!this.responseHea derMatch(request,"Cache-Control","(no-cache|no-store|must-revalidate)")||!!this. responseHeaderMatch(request,"Pragma","no-cache")||(hasExplicitExp&&!this.freshne ssLifetimeGreaterThan(request,0))||(!hasExplicitExp&&!!request.url&&request.url. indexOf("?")>=0)||(!hasExplicitExp&&!this.isCacheableResource(request));},isCach eableResource:function(request) 308 {var hasExplicitExp=this.hasExplicitExpiration(request);return!!this.responseHea derMatch(request,"Cache-Control","(no-cache|no-store|must-revalidate)")||!!this. responseHeaderMatch(request,"Pragma","no-cache")||(hasExplicitExp&&!this.freshne ssLifetimeGreaterThan(request,0))||(!hasExplicitExp&&!!request.url&&request.url. indexOf("?")>=0)||(!hasExplicitExp&&!this.isCacheableResource(request));},isCach eableResource:function(request)
305 {return request.statusCode!==undefined&&WebInspector.AuditRules.CacheableRespons eCodes[request.statusCode];},__proto__:WebInspector.AuditRule.prototype} 309 {return request.statusCode!==undefined&&WebInspector.AuditRules.CacheableRespons eCodes[request.statusCode];},__proto__:WebInspector.AuditRule.prototype}
306 WebInspector.AuditRules.BrowserCacheControlRule=function() 310 WebInspector.AuditRules.BrowserCacheControlRule=function()
307 {WebInspector.AuditRules.CacheControlRule.call(this,"http-browsercache",WebInspe ctor.UIString("Leverage browser caching"));} 311 {WebInspector.AuditRules.CacheControlRule.call(this,"http-browsercache",WebInspe ctor.UIString("Leverage browser caching"));}
308 WebInspector.AuditRules.BrowserCacheControlRule.prototype={handleNonCacheableRes ources:function(requests,result) 312 WebInspector.AuditRules.BrowserCacheControlRule.prototype={handleNonCacheableRes ources:function(requests,result)
309 {if(requests.length){var entry=result.addChild(WebInspector.UIString("The follow ing resources are explicitly non-cacheable. Consider making them cacheable if po ssible:"),true);result.violationCount+=requests.length;for(var i=0;i<requests.le ngth;++i) 313 {if(requests.length){var entry=result.addChild(WebInspector.UIString("The follow ing resources are explicitly non-cacheable. Consider making them cacheable if po ssible:"),true);result.violationCount+=requests.length;for(var i=0;i<requests.le ngth;++i)
310 entry.addURL(requests[i].url);}},runChecks:function(requests,result,callback) 314 entry.addURL(requests[i].url);}},runChecks:function(requests,result,callback)
311 {this.execCheck(WebInspector.UIString("The following resources are missing a cac he expiration. Resources that do not specify an expiration may not be cached by browsers:"),this._missingExpirationCheck,requests,result);this.execCheck(WebInsp ector.UIString("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:"),this._varyCheck,requests,result );this.execCheck(WebInspector.UIString("The following cacheable resources have a short freshness lifetime:"),this._oneMonthExpirationCheck,requests,result);this .execCheck(WebInspector.UIString("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:"),this. _oneYearExpirationCheck,requests,result);},_missingExpirationCheck:function(requ est) 315 {this.execCheck(WebInspector.UIString("The following resources are missing a cac he expiration. Resources that do not specify an expiration may not be cached by browsers:"),this._missingExpirationCheck,requests,result);this.execCheck(WebInsp ector.UIString("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:"),this._varyCheck,requests,result );this.execCheck(WebInspector.UIString("The following cacheable resources have a short freshness lifetime:"),this._oneMonthExpirationCheck,requests,result);this .execCheck(WebInspector.UIString("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:"),this. _oneYearExpirationCheck,requests,result);},_missingExpirationCheck:function(requ est)
(...skipping 10 matching lines...) Expand all
322 {return this.hasResponseHeader(request,"Set-Cookie")&&this.isPubliclyCacheable(r equest);},__proto__:WebInspector.AuditRules.CacheControlRule.prototype} 326 {return this.hasResponseHeader(request,"Set-Cookie")&&this.isPubliclyCacheable(r equest);},__proto__:WebInspector.AuditRules.CacheControlRule.prototype}
323 WebInspector.AuditRules.ImageDimensionsRule=function() 327 WebInspector.AuditRules.ImageDimensionsRule=function()
324 {WebInspector.AuditRule.call(this,"page-imagedims",WebInspector.UIString("Specif y image dimensions"));} 328 {WebInspector.AuditRule.call(this,"page-imagedims",WebInspector.UIString("Specif y image dimensions"));}
325 WebInspector.AuditRules.ImageDimensionsRule.prototype={doRun:function(requests,r esult,callback,progress) 329 WebInspector.AuditRules.ImageDimensionsRule.prototype={doRun:function(requests,r esult,callback,progress)
326 {var urlToNoDimensionCount={};function doneCallback() 330 {var urlToNoDimensionCount={};function doneCallback()
327 {for(var url in urlToNoDimensionCount){var entry=entry||result.addChild(WebInspe ctor.UIString("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height :"),true);var format="%r";if(urlToNoDimensionCount[url]>1) 331 {for(var url in urlToNoDimensionCount){var entry=entry||result.addChild(WebInspe ctor.UIString("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height :"),true);var format="%r";if(urlToNoDimensionCount[url]>1)
328 format+=" (%d uses)";entry.addFormatted(format,url,urlToNoDimensionCount[url]);r esult.violationCount++;} 332 format+=" (%d uses)";entry.addFormatted(format,url,urlToNoDimensionCount[url]);r esult.violationCount++;}
329 callback(entry?result:null);} 333 callback(entry?result:null);}
330 function imageStylesReady(imageId,styles,isLastStyle,computedStyle) 334 function imageStylesReady(imageId,styles,isLastStyle,computedStyle)
331 {if(progress.isCanceled()) 335 {if(progress.isCanceled())
332 return;const node=WebInspector.domAgent.nodeForId(imageId);var src=node.getAttri bute("src");if(!src.asParsedURL()){for(var frameOwnerCandidate=node;frameOwnerCa ndidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandida te.baseURL){var completeSrc=WebInspector.ParsedURL.completeURL(frameOwnerCandida te.baseURL,src);break;}}} 336 return;const node=WebInspector.domModel.nodeForId(imageId);var src=node.getAttri bute("src");if(!src.asParsedURL()){for(var frameOwnerCandidate=node;frameOwnerCa ndidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandida te.baseURL){var completeSrc=WebInspector.ParsedURL.completeURL(frameOwnerCandida te.baseURL,src);break;}}}
333 if(completeSrc) 337 if(completeSrc)
334 src=completeSrc;if(computedStyle.getPropertyValue("position")==="absolute"){if(i sLastStyle) 338 src=completeSrc;if(computedStyle.getPropertyValue("position")==="absolute"){if(i sLastStyle)
335 doneCallback();return;} 339 doneCallback();return;}
336 if(styles.attributesStyle){var widthFound=!!styles.attributesStyle.getLiveProper ty("width");var heightFound=!!styles.attributesStyle.getLiveProperty("height");} 340 if(styles.attributesStyle){var widthFound=!!styles.attributesStyle.getLiveProper ty("width");var heightFound=!!styles.attributesStyle.getLiveProperty("height");}
337 var inlineStyle=styles.inlineStyle;if(inlineStyle){if(inlineStyle.getPropertyVal ue("width")!=="") 341 var inlineStyle=styles.inlineStyle;if(inlineStyle){if(inlineStyle.getPropertyVal ue("width")!=="")
338 widthFound=true;if(inlineStyle.getPropertyValue("height")!=="") 342 widthFound=true;if(inlineStyle.getPropertyValue("height")!=="")
339 heightFound=true;} 343 heightFound=true;}
340 for(var i=styles.matchedCSSRules.length-1;i>=0&&!(widthFound&&heightFound);--i){ var style=styles.matchedCSSRules[i].style;if(style.getPropertyValue("width")!==" ") 344 for(var i=styles.matchedCSSRules.length-1;i>=0&&!(widthFound&&heightFound);--i){ var style=styles.matchedCSSRules[i].style;if(style.getPropertyValue("width")!==" ")
341 widthFound=true;if(style.getPropertyValue("height")!=="") 345 widthFound=true;if(style.getPropertyValue("height")!=="")
342 heightFound=true;} 346 heightFound=true;}
343 if(!widthFound||!heightFound){if(src in urlToNoDimensionCount) 347 if(!widthFound||!heightFound){if(src in urlToNoDimensionCount)
344 ++urlToNoDimensionCount[src];else 348 ++urlToNoDimensionCount[src];else
345 urlToNoDimensionCount[src]=1;} 349 urlToNoDimensionCount[src]=1;}
346 if(isLastStyle) 350 if(isLastStyle)
347 doneCallback();} 351 doneCallback();}
348 function getStyles(nodeIds) 352 function getStyles(nodeIds)
349 {if(progress.isCanceled()) 353 {if(progress.isCanceled())
350 return;var targetResult={};function inlineCallback(inlineStyle,attributesStyle) 354 return;var targetResult={};function inlineCallback(inlineStyle,attributesStyle)
351 {targetResult.inlineStyle=inlineStyle;targetResult.attributesStyle=attributesSty le;} 355 {targetResult.inlineStyle=inlineStyle;targetResult.attributesStyle=attributesSty le;}
352 function matchedCallback(result) 356 function matchedCallback(result)
353 {if(result) 357 {if(result)
354 targetResult.matchedCSSRules=result.matchedCSSRules;} 358 targetResult.matchedCSSRules=result.matchedCSSRules;}
355 if(!nodeIds||!nodeIds.length) 359 if(!nodeIds||!nodeIds.length)
356 doneCallback();for(var i=0;nodeIds&&i<nodeIds.length;++i){WebInspector.cssModel. getMatchedStylesAsync(nodeIds[i],false,false,matchedCallback);WebInspector.cssMo del.getInlineStylesAsync(nodeIds[i],inlineCallback);WebInspector.cssModel.getCom putedStyleAsync(nodeIds[i],imageStylesReady.bind(null,nodeIds[i],targetResult,i= ==nodeIds.length-1));}} 360 doneCallback();for(var i=0;nodeIds&&i<nodeIds.length;++i){WebInspector.cssModel. getMatchedStylesAsync(nodeIds[i],false,false,matchedCallback);WebInspector.cssMo del.getInlineStylesAsync(nodeIds[i],inlineCallback);WebInspector.cssModel.getCom putedStyleAsync(nodeIds[i],imageStylesReady.bind(null,nodeIds[i],targetResult,i= ==nodeIds.length-1));}}
357 function onDocumentAvailable(root) 361 function onDocumentAvailable(root)
358 {if(progress.isCanceled()) 362 {if(progress.isCanceled())
359 return;WebInspector.domAgent.querySelectorAll(root.id,"img[src]",getStyles);} 363 return;WebInspector.domModel.querySelectorAll(root.id,"img[src]",getStyles);}
360 if(progress.isCanceled()) 364 if(progress.isCanceled())
361 return;WebInspector.domAgent.requestDocument(onDocumentAvailable);},__proto__:We bInspector.AuditRule.prototype} 365 return;WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:We bInspector.AuditRule.prototype}
362 WebInspector.AuditRules.CssInHeadRule=function() 366 WebInspector.AuditRules.CssInHeadRule=function()
363 {WebInspector.AuditRule.call(this,"page-cssinhead",WebInspector.UIString("Put CS S in the document head"));} 367 {WebInspector.AuditRule.call(this,"page-cssinhead",WebInspector.UIString("Put CS S in the document head"));}
364 WebInspector.AuditRules.CssInHeadRule.prototype={doRun:function(requests,result, callback,progress) 368 WebInspector.AuditRules.CssInHeadRule.prototype={doRun:function(requests,result, callback,progress)
365 {function evalCallback(evalResult) 369 {function evalCallback(evalResult)
366 {if(progress.isCanceled()) 370 {if(progress.isCanceled())
367 return;if(!evalResult) 371 return;if(!evalResult)
368 return callback(null);var summary=result.addChild("");var outputMessages=[];for( var url in evalResult){var urlViolations=evalResult[url];if(urlViolations[0]){re sult.addFormatted("%s style block(s) in the %r body should be moved to the docum ent head.",urlViolations[0],url);result.violationCount+=urlViolations[0];} 372 return callback(null);var summary=result.addChild("");var outputMessages=[];for( var url in evalResult){var urlViolations=evalResult[url];if(urlViolations[0]){re sult.addFormatted("%s style block(s) in the %r body should be moved to the docum ent head.",urlViolations[0],url);result.violationCount+=urlViolations[0];}
369 for(var i=0;i<urlViolations[1].length;++i) 373 for(var i=0;i<urlViolations[1].length;++i)
370 result.addFormatted("Link node %r should be moved to the document head in %r",ur lViolations[1][i],url);result.violationCount+=urlViolations[1].length;} 374 result.addFormatted("Link node %r should be moved to the document head in %r",ur lViolations[1][i],url);result.violationCount+=urlViolations[1].length;}
371 summary.value=WebInspector.UIString("CSS in the document body adversely impacts rendering performance.");callback(result);} 375 summary.value=WebInspector.UIString("CSS in the document body adversely impacts rendering performance.");callback(result);}
372 function externalStylesheetsReceived(root,inlineStyleNodeIds,nodeIds) 376 function externalStylesheetsReceived(root,inlineStyleNodeIds,nodeIds)
373 {if(progress.isCanceled()) 377 {if(progress.isCanceled())
374 return;if(!nodeIds) 378 return;if(!nodeIds)
375 return;var externalStylesheetNodeIds=nodeIds;var result=null;if(inlineStyleNodeI ds.length||externalStylesheetNodeIds.length){var urlToViolationsArray={};var ext ernalStylesheetHrefs=[];for(var j=0;j<externalStylesheetNodeIds.length;++j){var linkNode=WebInspector.domAgent.nodeForId(externalStylesheetNodeIds[j]);var compl eteHref=WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL,linkNo de.getAttribute("href"));externalStylesheetHrefs.push(completeHref||"<empty>");} 379 return;var externalStylesheetNodeIds=nodeIds;var result=null;if(inlineStyleNodeI ds.length||externalStylesheetNodeIds.length){var urlToViolationsArray={};var ext ernalStylesheetHrefs=[];for(var j=0;j<externalStylesheetNodeIds.length;++j){var linkNode=WebInspector.domModel.nodeForId(externalStylesheetNodeIds[j]);var compl eteHref=WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL,linkNo de.getAttribute("href"));externalStylesheetHrefs.push(completeHref||"<empty>");}
376 urlToViolationsArray[root.documentURL]=[inlineStyleNodeIds.length,externalStyles heetHrefs];result=urlToViolationsArray;} 380 urlToViolationsArray[root.documentURL]=[inlineStyleNodeIds.length,externalStyles heetHrefs];result=urlToViolationsArray;}
377 evalCallback(result);} 381 evalCallback(result);}
378 function inlineStylesReceived(root,nodeIds) 382 function inlineStylesReceived(root,nodeIds)
379 {if(progress.isCanceled()) 383 {if(progress.isCanceled())
380 return;if(!nodeIds) 384 return;if(!nodeIds)
381 return;WebInspector.domAgent.querySelectorAll(root.id,"body link[rel~='styleshee t'][href]",externalStylesheetsReceived.bind(null,root,nodeIds));} 385 return;WebInspector.domModel.querySelectorAll(root.id,"body link[rel~='styleshee t'][href]",externalStylesheetsReceived.bind(null,root,nodeIds));}
382 function onDocumentAvailable(root) 386 function onDocumentAvailable(root)
383 {if(progress.isCanceled()) 387 {if(progress.isCanceled())
384 return;WebInspector.domAgent.querySelectorAll(root.id,"body style",inlineStylesR eceived.bind(null,root));} 388 return;WebInspector.domModel.querySelectorAll(root.id,"body style",inlineStylesR eceived.bind(null,root));}
385 WebInspector.domAgent.requestDocument(onDocumentAvailable);},__proto__:WebInspec tor.AuditRule.prototype} 389 WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:WebInspec tor.AuditRule.prototype}
386 WebInspector.AuditRules.StylesScriptsOrderRule=function() 390 WebInspector.AuditRules.StylesScriptsOrderRule=function()
387 {WebInspector.AuditRule.call(this,"page-stylescriptorder",WebInspector.UIString( "Optimize the order of styles and scripts"));} 391 {WebInspector.AuditRule.call(this,"page-stylescriptorder",WebInspector.UIString( "Optimize the order of styles and scripts"));}
388 WebInspector.AuditRules.StylesScriptsOrderRule.prototype={doRun:function(request s,result,callback,progress) 392 WebInspector.AuditRules.StylesScriptsOrderRule.prototype={doRun:function(request s,result,callback,progress)
389 {function evalCallback(resultValue) 393 {function evalCallback(resultValue)
390 {if(progress.isCanceled()) 394 {if(progress.isCanceled())
391 return;if(!resultValue) 395 return;if(!resultValue)
392 return callback(null);var lateCssUrls=resultValue[0];var cssBeforeInlineCount=re sultValue[1];if(lateCssUrls.length){var entry=result.addChild(WebInspector.UIStr ing("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, alwa ys include external CSS before external JavaScript."),true);entry.addURLs(lateCs sUrls);result.violationCount+=lateCssUrls.length;} 396 return callback(null);var lateCssUrls=resultValue[0];var cssBeforeInlineCount=re sultValue[1];if(lateCssUrls.length){var entry=result.addChild(WebInspector.UIStr ing("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, alwa ys include external CSS before external JavaScript."),true);entry.addURLs(lateCs sUrls);result.violationCount+=lateCssUrls.length;}
393 if(cssBeforeInlineCount){result.addChild(WebInspector.UIString(" %d inline scrip t block%s found in the head between an external CSS file and another resource. T o allow parallel downloading, move the inline script before the external CSS fil e, or after the next resource.",cssBeforeInlineCount,cssBeforeInlineCount>1?"s w ere":" was"));result.violationCount+=cssBeforeInlineCount;} 397 if(cssBeforeInlineCount){result.addChild(WebInspector.UIString(" %d inline scrip t block%s found in the head between an external CSS file and another resource. T o allow parallel downloading, move the inline script before the external CSS fil e, or after the next resource.",cssBeforeInlineCount,cssBeforeInlineCount>1?"s w ere":" was"));result.violationCount+=cssBeforeInlineCount;}
394 callback(result);} 398 callback(result);}
395 function cssBeforeInlineReceived(lateStyleIds,nodeIds) 399 function cssBeforeInlineReceived(lateStyleIds,nodeIds)
396 {if(progress.isCanceled()) 400 {if(progress.isCanceled())
397 return;if(!nodeIds) 401 return;if(!nodeIds)
398 return;var cssBeforeInlineCount=nodeIds.length;var result=null;if(lateStyleIds.l ength||cssBeforeInlineCount){var lateStyleUrls=[];for(var i=0;i<lateStyleIds.len gth;++i){var lateStyleNode=WebInspector.domAgent.nodeForId(lateStyleIds[i]);var completeHref=WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.base URL,lateStyleNode.getAttribute("href"));lateStyleUrls.push(completeHref||"<empty >");} 402 return;var cssBeforeInlineCount=nodeIds.length;var result=null;if(lateStyleIds.l ength||cssBeforeInlineCount){var lateStyleUrls=[];for(var i=0;i<lateStyleIds.len gth;++i){var lateStyleNode=WebInspector.domModel.nodeForId(lateStyleIds[i]);var completeHref=WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.base URL,lateStyleNode.getAttribute("href"));lateStyleUrls.push(completeHref||"<empty >");}
399 result=[lateStyleUrls,cssBeforeInlineCount];} 403 result=[lateStyleUrls,cssBeforeInlineCount];}
400 evalCallback(result);} 404 evalCallback(result);}
401 function lateStylesReceived(root,nodeIds) 405 function lateStylesReceived(root,nodeIds)
402 {if(progress.isCanceled()) 406 {if(progress.isCanceled())
403 return;if(!nodeIds) 407 return;if(!nodeIds)
404 return;WebInspector.domAgent.querySelectorAll(root.id,"head link[rel~='styleshee t'][href] ~ script:not([src])",cssBeforeInlineReceived.bind(null,nodeIds));} 408 return;WebInspector.domModel.querySelectorAll(root.id,"head link[rel~='styleshee t'][href] ~ script:not([src])",cssBeforeInlineReceived.bind(null,nodeIds));}
405 function onDocumentAvailable(root) 409 function onDocumentAvailable(root)
406 {if(progress.isCanceled()) 410 {if(progress.isCanceled())
407 return;WebInspector.domAgent.querySelectorAll(root.id,"head script[src] ~ link[r el~='stylesheet'][href]",lateStylesReceived.bind(null,root));} 411 return;WebInspector.domModel.querySelectorAll(root.id,"head script[src] ~ link[r el~='stylesheet'][href]",lateStylesReceived.bind(null,root));}
408 WebInspector.domAgent.requestDocument(onDocumentAvailable);},__proto__:WebInspec tor.AuditRule.prototype} 412 WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:WebInspec tor.AuditRule.prototype}
409 WebInspector.AuditRules.CSSRuleBase=function(id,name) 413 WebInspector.AuditRules.CSSRuleBase=function(id,name)
410 {WebInspector.AuditRule.call(this,id,name);} 414 {WebInspector.AuditRule.call(this,id,name);}
411 WebInspector.AuditRules.CSSRuleBase.prototype={doRun:function(requests,result,ca llback,progress) 415 WebInspector.AuditRules.CSSRuleBase.prototype={doRun:function(requests,result,ca llback,progress)
412 {CSSAgent.getAllStyleSheets(sheetsCallback.bind(this));function sheetsCallback(e rror,headers) 416 {var headers=WebInspector.cssModel.allStyleSheets();if(!headers.length){callback (null);return;}
413 {if(error) 417 var activeHeaders=[]
414 return callback(null);if(!headers.length) 418 for(var i=0;i<headers.length;++i){if(!headers[i].disabled)
415 return callback(null);for(var i=0;i<headers.length;++i){var header=headers[i];if (header.disabled) 419 activeHeaders.push(headers[i]);}
416 continue;this._visitStyleSheet(header.styleSheetId,i===headers.length-1?finished Callback:null,result,progress);}} 420 var styleSheetProcessor=new WebInspector.AuditRules.StyleSheetProcessor(activeHe aders,progress,this._styleSheetsLoaded.bind(this,result,callback,progress));styl eSheetProcessor.run();},_styleSheetsLoaded:function(result,callback,progress,sty leSheets)
417 function finishedCallback() 421 {for(var i=0;i<styleSheets.length;++i)
418 {callback(result);}},_visitStyleSheet:function(styleSheetId,callback,result,prog ress) 422 this._visitStyleSheet(styleSheets[i],result);callback(result);},_visitStyleSheet :function(styleSheet,result)
419 {WebInspector.CSSStyleSheet.createForId(styleSheetId,sheetCallback.bind(this));f unction sheetCallback(styleSheet) 423 {this.visitStyleSheet(styleSheet,result);for(var i=0;i<styleSheet.rules.length;+ +i)
420 {if(progress.isCanceled()) 424 this._visitRule(styleSheet,styleSheet.rules[i],result);this.didVisitStyleSheet(s tyleSheet,result);},_visitRule:function(styleSheet,rule,result)
421 return;if(!styleSheet){if(callback) 425 {this.visitRule(styleSheet,rule,result);var allProperties=rule.properties;for(va r i=0;i<allProperties.length;++i)
422 callback();return;} 426 this.visitProperty(styleSheet,rule,allProperties[i],result);this.didVisitRule(st yleSheet,rule,result);},visitStyleSheet:function(styleSheet,result)
423 this.visitStyleSheet(styleSheet,result);for(var i=0;i<styleSheet.rules.length;++ i)
424 this._visitRule(styleSheet,styleSheet.rules[i],result);this.didVisitStyleSheet(s tyleSheet,result);if(callback)
425 callback();}},_visitRule:function(styleSheet,rule,result)
426 {this.visitRule(styleSheet,rule,result);var allProperties=rule.style.allProperti es;for(var i=0;i<allProperties.length;++i)
427 this.visitProperty(styleSheet,allProperties[i],result);this.didVisitRule(styleSh eet,rule,result);},visitStyleSheet:function(styleSheet,result)
428 {},didVisitStyleSheet:function(styleSheet,result) 427 {},didVisitStyleSheet:function(styleSheet,result)
429 {},visitRule:function(styleSheet,rule,result) 428 {},visitRule:function(styleSheet,rule,result)
430 {},didVisitRule:function(styleSheet,rule,result) 429 {},didVisitRule:function(styleSheet,rule,result)
431 {},visitProperty:function(styleSheet,property,result) 430 {},visitProperty:function(styleSheet,rule,property,result)
432 {},__proto__:WebInspector.AuditRule.prototype} 431 {},__proto__:WebInspector.AuditRule.prototype}
433 WebInspector.AuditRules.VendorPrefixedCSSProperties=function() 432 WebInspector.AuditRules.VendorPrefixedCSSProperties=function()
434 {WebInspector.AuditRules.CSSRuleBase.call(this,"page-vendorprefixedcss",WebInspe ctor.UIString("Use normal CSS property names instead of vendor-prefixed ones")); this._webkitPrefix="-webkit-";} 433 {WebInspector.AuditRules.CSSRuleBase.call(this,"page-vendorprefixedcss",WebInspe ctor.UIString("Use normal CSS property names instead of vendor-prefixed ones")); this._webkitPrefix="-webkit-";}
435 WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties=["backgr ound-clip","background-origin","background-size","border-radius","border-bottom- left-radius","border-bottom-right-radius","border-top-left-radius","border-top-r ight-radius","box-shadow","box-sizing","opacity","text-shadow"].keySet();WebInsp ector.AuditRules.VendorPrefixedCSSProperties.prototype={didVisitStyleSheet:funct ion(styleSheet) 434 WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties=["backgr ound-clip","background-origin","background-size","border-radius","border-bottom- left-radius","border-bottom-right-radius","border-top-left-radius","border-top-r ight-radius","box-shadow","box-sizing","opacity","text-shadow"].keySet();WebInsp ector.AuditRules.VendorPrefixedCSSProperties.prototype={didVisitStyleSheet:funct ion(styleSheet)
436 {delete this._styleSheetResult;},visitRule:function(rule) 435 {delete this._styleSheetResult;},visitRule:function(rule)
437 {this._mentionedProperties={};},didVisitRule:function() 436 {this._mentionedProperties={};},didVisitRule:function()
438 {delete this._ruleResult;delete this._mentionedProperties;},visitProperty:functi on(styleSheet,property,result) 437 {delete this._ruleResult;delete this._mentionedProperties;},visitProperty:functi on(styleSheet,rule,property,result)
439 {if(!property.name.startsWith(this._webkitPrefix)) 438 {if(!property.name.startsWith(this._webkitPrefix))
440 return;var normalPropertyName=property.name.substring(this._webkitPrefix.length) .toLowerCase();if(WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedP roperties[normalPropertyName]&&!this._mentionedProperties[normalPropertyName]){v ar style=property.ownerStyle;var liveProperty=style.getLiveProperty(normalProper tyName);if(liveProperty&&!liveProperty.styleBased) 439 return;var normalPropertyName=property.name.substring(this._webkitPrefix.length) .toLowerCase();if(WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedP roperties[normalPropertyName]&&!this._mentionedProperties[normalPropertyName]){t his._mentionedProperties[normalPropertyName]=true;if(!this._styleSheetResult)
441 return;var rule=style.parentRule;this._mentionedProperties[normalPropertyName]=t rue;if(!this._styleSheetResult) 440 this._styleSheetResult=result.addChild(styleSheet.sourceURL?WebInspector.linkify ResourceAsNode(styleSheet.sourceURL):WebInspector.UIString("<unknown>"));if(!thi s._ruleResult){var anchor=WebInspector.linkifyURLAsNode(styleSheet.sourceURL,rul e.selectorText);anchor.lineNumber=rule.lineNumber;this._ruleResult=this._styleSh eetResult.addChild(anchor);}
442 this._styleSheetResult=result.addChild(rule.sourceURL?WebInspector.linkifyResour ceAsNode(rule.sourceURL):WebInspector.UIString("<unknown>"));if(!this._ruleResul t){var anchor=WebInspector.linkifyURLAsNode(rule.sourceURL,rule.selectorText);an chor.preferredPanel="resources";anchor.lineNumber=rule.lineNumberInSource();this ._ruleResult=this._styleSheetResult.addChild(anchor);}
443 ++result.violationCount;this._ruleResult.addSnippet(WebInspector.UIString("\"%s% s\" is used, but \"%s\" is supported.",this._webkitPrefix,normalPropertyName,nor malPropertyName));}},__proto__:WebInspector.AuditRules.CSSRuleBase.prototype} 441 ++result.violationCount;this._ruleResult.addSnippet(WebInspector.UIString("\"%s% s\" is used, but \"%s\" is supported.",this._webkitPrefix,normalPropertyName,nor malPropertyName));}},__proto__:WebInspector.AuditRules.CSSRuleBase.prototype}
444 WebInspector.AuditRules.CookieRuleBase=function(id,name) 442 WebInspector.AuditRules.CookieRuleBase=function(id,name)
445 {WebInspector.AuditRule.call(this,id,name);} 443 {WebInspector.AuditRule.call(this,id,name);}
446 WebInspector.AuditRules.CookieRuleBase.prototype={doRun:function(requests,result ,callback,progress) 444 WebInspector.AuditRules.CookieRuleBase.prototype={doRun:function(requests,result ,callback,progress)
447 {var self=this;function resultCallback(receivedCookies){if(progress.isCanceled() ) 445 {var self=this;function resultCallback(receivedCookies){if(progress.isCanceled() )
448 return;self.processCookies(receivedCookies,requests,result);callback(result);} 446 return;self.processCookies(receivedCookies,requests,result);callback(result);}
449 WebInspector.Cookies.getCookiesAsync(resultCallback);},mapResourceCookies:functi on(requestsByDomain,allCookies,callback) 447 WebInspector.Cookies.getCookiesAsync(resultCallback);},mapResourceCookies:functi on(requestsByDomain,allCookies,callback)
450 {for(var i=0;i<allCookies.length;++i){for(var requestDomain in requestsByDomain) {if(WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain( ),requestDomain)) 448 {for(var i=0;i<allCookies.length;++i){for(var requestDomain in requestsByDomain) {if(WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain( ),requestDomain))
451 this._callbackForResourceCookiePairs(requestsByDomain[requestDomain],allCookies[ i],callback);}}},_callbackForResourceCookiePairs:function(requests,cookie,callba ck) 449 this._callbackForResourceCookiePairs(requestsByDomain[requestDomain],allCookies[ i],callback);}}},_callbackForResourceCookiePairs:function(requests,cookie,callba ck)
452 {if(!requests) 450 {if(!requests)
453 return;for(var i=0;i<requests.length;++i){if(WebInspector.Cookies.cookieMatchesR esourceURL(cookie,requests[i].url)) 451 return;for(var i=0;i<requests.length;++i){if(WebInspector.Cookies.cookieMatchesR esourceURL(cookie,requests[i].url))
454 callback(requests[i],cookie);}},__proto__:WebInspector.AuditRule.prototype} 452 callback(requests[i],cookie);}},__proto__:WebInspector.AuditRule.prototype}
455 WebInspector.AuditRules.CookieSizeRule=function(avgBytesThreshold) 453 WebInspector.AuditRules.CookieSizeRule=function(avgBytesThreshold)
456 {WebInspector.AuditRules.CookieRuleBase.call(this,"http-cookiesize",WebInspector .UIString("Minimize cookie size"));this._avgBytesThreshold=avgBytesThreshold;thi s._maxBytesThreshold=1000;} 454 {WebInspector.AuditRules.CookieRuleBase.call(this,"http-cookiesize",WebInspector .UIString("Minimize cookie size"));this._avgBytesThreshold=avgBytesThreshold;thi s._maxBytesThreshold=1000;}
457 WebInspector.AuditRules.CookieSizeRule.prototype={_average:function(cookieArray) 455 WebInspector.AuditRules.CookieSizeRule.prototype={_average:function(cookieArray)
458 {var total=0;for(var i=0;i<cookieArray.length;++i) 456 {var total=0;for(var i=0;i<cookieArray.length;++i)
459 total+=cookieArray[i].size();return cookieArray.length?Math.round(total/cookieAr ray.length):0;},_max:function(cookieArray) 457 total+=cookieArray[i].size();return cookieArray.length?Math.round(total/cookieAr ray.length):0;},_max:function(cookieArray)
460 {var result=0;for(var i=0;i<cookieArray.length;++i) 458 {var result=0;for(var i=0;i<cookieArray.length;++i)
461 result=Math.max(cookieArray[i].size(),result);return result;},processCookies:fun ction(allCookies,requests,result) 459 result=Math.max(cookieArray[i].size(),result);return result;},processCookies:fun ction(allCookies,requests,result)
462 {function maxSizeSorter(a,b) 460 {function maxSizeSorter(a,b)
463 {return b.maxCookieSize-a.maxCookieSize;} 461 {return b.maxCookieSize-a.maxCookieSize;}
464 function avgSizeSorter(a,b) 462 function avgSizeSorter(a,b)
465 {return b.avgCookieSize-a.avgCookieSize;} 463 {return b.avgCookieSize-a.avgCookieSize;}
466 var cookiesPerResourceDomain={};function collectorCallback(request,cookie) 464 var cookiesPerResourceDomain={};function collectorCallback(request,cookie)
467 {var cookies=cookiesPerResourceDomain[request.parsedURL.host];if(!cookies){cooki es=[];cookiesPerResourceDomain[request.parsedURL.host]=cookies;} 465 {var cookies=cookiesPerResourceDomain[request.parsedURL.host];if(!cookies){cooki es=[];cookiesPerResourceDomain[request.parsedURL.host]=cookies;}
468 cookies.push(cookie);} 466 cookies.push(cookie);}
469 if(!allCookies.length) 467 if(!allCookies.length)
470 return;var sortedCookieSizes=[];var domainToResourcesMap=WebInspector.AuditRules .getDomainToResourcesMap(requests,null,true);var matchingResourceData={};this.ma pResourceCookies(domainToResourcesMap,allCookies,collectorCallback.bind(this));f or(var requestDomain in cookiesPerResourceDomain){var cookies=cookiesPerResource Domain[requestDomain];sortedCookieSizes.push({domain:requestDomain,avgCookieSize :this._average(cookies),maxCookieSize:this._max(cookies)});} 468 return;var sortedCookieSizes=[];var domainToResourcesMap=WebInspector.AuditRules .getDomainToResourcesMap(requests,null,true);var matchingResourceData={};this.ma pResourceCookies(domainToResourcesMap,allCookies,collectorCallback);for(var requ estDomain in cookiesPerResourceDomain){var cookies=cookiesPerResourceDomain[requ estDomain];sortedCookieSizes.push({domain:requestDomain,avgCookieSize:this._aver age(cookies),maxCookieSize:this._max(cookies)});}
471 var avgAllCookiesSize=this._average(allCookies);var hugeCookieDomains=[];sortedC ookieSizes.sort(maxSizeSorter);for(var i=0,len=sortedCookieSizes.length;i<len;++ i){var maxCookieSize=sortedCookieSizes[i].maxCookieSize;if(maxCookieSize>this._m axBytesThreshold) 469 var avgAllCookiesSize=this._average(allCookies);var hugeCookieDomains=[];sortedC ookieSizes.sort(maxSizeSorter);for(var i=0,len=sortedCookieSizes.length;i<len;++ i){var maxCookieSize=sortedCookieSizes[i].maxCookieSize;if(maxCookieSize>this._m axBytesThreshold)
472 hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieS izes[i].domain)+": "+Number.bytesToString(maxCookieSize));} 470 hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieS izes[i].domain)+": "+Number.bytesToString(maxCookieSize));}
473 var bigAvgCookieDomains=[];sortedCookieSizes.sort(avgSizeSorter);for(var i=0,len =sortedCookieSizes.length;i<len;++i){var domain=sortedCookieSizes[i].domain;var avgCookieSize=sortedCookieSizes[i].avgCookieSize;if(avgCookieSize>this._avgBytes Threshold&&avgCookieSize<this._maxBytesThreshold) 471 var bigAvgCookieDomains=[];sortedCookieSizes.sort(avgSizeSorter);for(var i=0,len =sortedCookieSizes.length;i<len;++i){var domain=sortedCookieSizes[i].domain;var avgCookieSize=sortedCookieSizes[i].avgCookieSize;if(avgCookieSize>this._avgBytes Threshold&&avgCookieSize<this._maxBytesThreshold)
474 bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain)+": "+Number.bytesToString(avgCookieSize));} 472 bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain)+": "+Number.bytesToString(avgCookieSize));}
475 result.addChild(WebInspector.UIString("The average cookie size for all requests on this page is %s",Number.bytesToString(avgAllCookiesSize)));var message;if(hug eCookieDomains.length){var entry=result.addChild(WebInspector.UIString("The foll owing domains have a cookie size in excess of 1KB. This is harmful because reque sts with cookies larger than 1KB typically cannot fit into a single network pack et."),true);entry.addURLs(hugeCookieDomains);result.violationCount+=hugeCookieDo mains.length;} 473 result.addChild(WebInspector.UIString("The average cookie size for all requests on this page is %s",Number.bytesToString(avgAllCookiesSize)));var message;if(hug eCookieDomains.length){var entry=result.addChild(WebInspector.UIString("The foll owing domains have a cookie size in excess of 1KB. This is harmful because reque sts with cookies larger than 1KB typically cannot fit into a single network pack et."),true);entry.addURLs(hugeCookieDomains);result.violationCount+=hugeCookieDo mains.length;}
476 if(bigAvgCookieDomains.length){var entry=result.addChild(WebInspector.UIString(" The following domains have an average cookie size in excess of %d bytes. Reducin g the size of cookies for these domains can reduce the time it takes to send req uests.",this._avgBytesThreshold),true);entry.addURLs(bigAvgCookieDomains);result .violationCount+=bigAvgCookieDomains.length;}},__proto__:WebInspector.AuditRules .CookieRuleBase.prototype} 474 if(bigAvgCookieDomains.length){var entry=result.addChild(WebInspector.UIString(" The following domains have an average cookie size in excess of %d bytes. Reducin g the size of cookies for these domains can reduce the time it takes to send req uests.",this._avgBytesThreshold),true);entry.addURLs(bigAvgCookieDomains);result .violationCount+=bigAvgCookieDomains.length;}},__proto__:WebInspector.AuditRules .CookieRuleBase.prototype}
477 WebInspector.AuditRules.StaticCookielessRule=function(minResources) 475 WebInspector.AuditRules.StaticCookielessRule=function(minResources)
478 {WebInspector.AuditRules.CookieRuleBase.call(this,"http-staticcookieless",WebIns pector.UIString("Serve static content from a cookieless domain"));this._minResou rces=minResources;} 476 {WebInspector.AuditRules.CookieRuleBase.call(this,"http-staticcookieless",WebIns pector.UIString("Serve static content from a cookieless domain"));this._minResou rces=minResources;}
479 WebInspector.AuditRules.StaticCookielessRule.prototype={processCookies:function( allCookies,requests,result) 477 WebInspector.AuditRules.StaticCookielessRule.prototype={processCookies:function( allCookies,requests,result)
480 {var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(reques ts,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true );var totalStaticResources=0;for(var domain in domainToResourcesMap) 478 {var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(reques ts,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true );var totalStaticResources=0;for(var domain in domainToResourcesMap)
481 totalStaticResources+=domainToResourcesMap[domain].length;if(totalStaticResource s<this._minResources) 479 totalStaticResources+=domainToResourcesMap[domain].length;if(totalStaticResource s<this._minResources)
482 return;var matchingResourceData={};this.mapResourceCookies(domainToResourcesMap, allCookies,this._collectorCallback.bind(this,matchingResourceData));var badUrls= [];var cookieBytes=0;for(var url in matchingResourceData){badUrls.push(url);cook ieBytes+=matchingResourceData[url]} 480 return;var matchingResourceData={};this.mapResourceCookies(domainToResourcesMap, allCookies,this._collectorCallback.bind(this,matchingResourceData));var badUrls= [];var cookieBytes=0;for(var url in matchingResourceData){badUrls.push(url);cook ieBytes+=matchingResourceData[url]}
483 if(badUrls.length<this._minResources) 481 if(badUrls.length<this._minResources)
484 return;var entry=result.addChild(WebInspector.UIString("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:",Number.bytesToString(cookieBytes)),true);entry.addUR Ls(badUrls);result.violationCount=badUrls.length;},_collectorCallback:function(m atchingResourceData,request,cookie) 482 return;var entry=result.addChild(WebInspector.UIString("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:",Number.bytesToString(cookieBytes)),true);entry.addUR Ls(badUrls);result.violationCount=badUrls.length;},_collectorCallback:function(m atchingResourceData,request,cookie)
485 {matchingResourceData[request.url]=(matchingResourceData[request.url]||0)+cookie .size();},__proto__:WebInspector.AuditRules.CookieRuleBase.prototype}; 483 {matchingResourceData[request.url]=(matchingResourceData[request.url]||0)+cookie .size();},__proto__:WebInspector.AuditRules.CookieRuleBase.prototype};
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698