Permalink
Browse files

Google Page Speed adjustments

  • Loading branch information...
Thomas Tyack
Thomas Tyack committed Mar 21, 2018
1 parent 44a5ff5 commit df6f2e550da1cd350b2c28ec81fd205e941a4f1e
@@ -1,11 +1,14 @@
namespace Sitecore.Foundation.Assets.Services
using Sitecore.Data.Items;
namespace Sitecore.Foundation.Assets.Services
{
using System;
using System.Linq;
using System.Text;
using System.Web;
using Sitecore.Foundation.Assets.Models;
using Sitecore.Foundation.Assets.Repositories;
using Sitecore.Foundation.SitecoreExtensions.Extensions;
/// <summary>
/// A service which helps add the required JavaScript at the end of a page, and CSS at the top of a page.
@@ -54,15 +57,16 @@ public HtmlString RenderScript(ScriptLocation location)
return new HtmlString(sb.ToString());
}
public HtmlString RenderStyles()
public HtmlString RenderStyles(bool async)
{
var sb = new StringBuilder();
string asyncVal = async.ToString().ToLower();
foreach (var item in AssetRepository.Current.Items.Where(asset => asset.Type == AssetType.Css && this.IsForContextSite(asset)))
{
switch (item.ContentType)
{
case AssetContentType.File:
sb.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" />", item.Content).AppendLine();
sb.AppendFormat($"<link href=\"{0}\" rel=\"stylesheet\" async=\"{asyncVal}\" />", item.Content).AppendLine();
break;
case AssetContentType.Inline:
sb.AppendLine("<style type=\"text/css\">");
@@ -94,5 +98,60 @@ private bool IsForContextSite(Asset asset)
}
return false;
}
public bool HasInlineStyles(HttpRequestBase request)
{
return AssetRepository.Current.Items.Any(asset => asset.Type == AssetType.Css && asset.ContentType == AssetContentType.Inline && this.IsForContextSite(asset));
}
public HtmlString RenderScriptAsyncBootup(ScriptLocation location, string jqueryLocation)
{
var sb = new StringBuilder();
var assets = AssetRepository.Current.Items.Where(
asset => (asset.Type == AssetType.JavaScript || asset.Type == AssetType.Raw)
&& asset.Location == location && this.IsForContextSite(asset));
sb.Append("<script data-cfasync=\"false\">\n var scriptsToLoad = [");
var assetsArray = assets as Asset[] ?? assets.ToArray();
for (int i = 0; i < assetsArray.Count(); i++)
{
var sciptUri = assetsArray[i].Content;
if (!string.IsNullOrWhiteSpace(sciptUri))
{
sb.Append($"'{sciptUri.Replace("\r", string.Empty)}'");
if (assetsArray.Any() && (i + 1) != assetsArray.Count())
{
sb.Append(",");
}
}
}
sb.Append("]; \n</script>");
sb.AppendLine($"<script data-cfasync=\"false\" src=\"{jqueryLocation}\" async defer></script> ");
return new HtmlString(sb.ToString());
}
public static string GetPageKey(Item item)
{
string key = string.Empty;
if (item.Url() == "/" || item.Name == "Home")
key = "homepage";
else
{
key = item.Url().Replace("/", "_");
}
return key;
}
public static string GetPageKey(HttpRequestBase request)
{
string key = request.Url.PathAndQuery;
if (key == "/")
key = "homepage";
else
{
key = request.Url.PathAndQuery.Replace("/", "_");
}
return key;
}
}
}
@@ -1,32 +1,61 @@
namespace Sitecore.Foundation.SitecoreExtensions.Extensions
{
using System;
using Sitecore.Mvc.Presentation;
using Sitecore.Resources.Media;
using Sitecore.Xml;
public static class RenderingExtensions
{
public static int GetIntegerParameter(this Rendering rendering, string parameterName, int defaultValue = 0)
using System;
using System.Web;
using Sitecore.Mvc.Helpers;
using Sitecore.Mvc.Presentation;
using Sitecore.Resources.Media;
using Sitecore.Xml;
public static class RenderingExtensions
{
if (rendering == null)
{
throw new ArgumentNullException(nameof(rendering));
}
var parameter = rendering.Parameters[parameterName];
if (string.IsNullOrEmpty(parameter))
{
return defaultValue;
}
int returnValue;
return !int.TryParse(parameter, out returnValue) ? defaultValue : returnValue;
public static int GetIntegerParameter(this Rendering rendering, string parameterName, int defaultValue = 0)
{
if (rendering == null)
{
throw new ArgumentNullException(nameof(rendering));
}
var parameter = rendering.Parameters[parameterName];
if (string.IsNullOrEmpty(parameter))
{
return defaultValue;
}
int returnValue;
return !int.TryParse(parameter, out returnValue) ? defaultValue : returnValue;
}
public static bool GetUseStaticPlaceholderNames([NotNull] this Rendering rendering)
{
return MainUtil.GetBool(rendering.Parameters[Constants.DynamicPlaceholdersLayoutParameters.UseStaticPlaceholderNames], false);
}
public static HtmlString CachedRendering(this SitecoreHelper sitecoreHelper, string pathOrId, RenderingCachingSettings renderingCachingSettings)
{
return sitecoreHelper.Rendering(pathOrId, renderingCachingSettings);
}
}
public static bool GetUseStaticPlaceholderNames([NotNull] this Rendering rendering)
public class RenderingCachingSettings
{
return MainUtil.GetBool(rendering.Parameters[Constants.DynamicPlaceholdersLayoutParameters.UseStaticPlaceholderNames], false);
public bool? Cacheable { get; set; }
public TimeSpan? Cache_Timeout { get; set; }
public bool? Cache_VaryByData { get; set; }
public bool? Cache_VaryByDevice { get; set; }
public bool? Cache_VaryByLogin { get; set; }
public bool? Cache_VaryByParameters { get; set; }
public bool? Cache_VaryByQueryString { get; set; }
public bool? Cache_VaryByUser { get; set; }
public string CacheKey { get; set; }
}
}
}
@@ -265,6 +265,10 @@
<Content Include="styles\dayfrost\components\atoms\_button.scss" />
<Content Include="styles\dayfrost\components\atoms\_well.scss" />
<Content Include="styles\dayfrost\components\_atoms.scss" />
<Content Include="Views\Common\Assets\InlineStyles.cshtml" />
<Content Include="Views\Common\Assets\Scripts-3.2.1.cshtml" />
<Content Include="Views\Common\Assets\Styles.cshtml" />
<Content Include="Views\Common\Assets\StylesDeferred.cshtml" />
<None Include="Views\Web.config" />
<None Include="web.config" />
<None Include="web.Debug.config">
@@ -275,6 +279,10 @@
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\foundation\Assets\code\Sitecore.Foundation.Assets.csproj">
<Project>{7E46FF93-EE05-412C-AC47-2A59A13DA73C}</Project>
<Name>Sitecore.Foundation.Assets</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\foundation\SitecoreExtensions\code\Sitecore.Foundation.SitecoreExtensions.csproj">
<Project>{b535703f-8d07-4f23-a533-2974bb4cc7b1}</Project>
<Name>Sitecore.Foundation.SitecoreExtensions</Name>
@@ -284,7 +292,9 @@
<Name>Sitecore.Foundation.Theming</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Folder Include="assets\js\lib\" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
@@ -0,0 +1,5 @@
@model Sitecore.Mvc.Presentation.RenderingModel
@using Sitecore.Foundation.Assets.Services
<!-- Inline Viewport CSS | above the fold -->
@RenderAssetsService.Current.RenderInlineStyles(Request)
@@ -0,0 +1,6 @@
@using Sitecore.Foundation.Assets.Models
@using Sitecore.Foundation.Assets.Services
@model Sitecore.Mvc.Presentation.RenderingModel
<!-- Latest compiled and minified JavaScript -->
@RenderAssetsService.Current.RenderScriptAsyncBootup(ScriptLocation.Body, "/scripts/jquery-3.2.1.min.js?v=2")
@@ -0,0 +1,4 @@
@model Sitecore.Mvc.Presentation.RenderingModel
@using Sitecore.Foundation.Assets.Services
@RenderAssetsService.Current.RenderStyles(false)
@@ -0,0 +1,28 @@
@using Sitecore.Foundation.Assets.Services
@model Sitecore.Mvc.Presentation.RenderingModel
@if (RenderAssetsService.Current.HasInlineStyles(Request))
{
<noscript id="deferred-styles">
@*Styles*@
@RenderAssetsService.Current.RenderStyles(true)
</noscript>
<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement);
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
else window.addEventListener('load', loadDeferredStyles);
</script>
}
else
{
@RenderAssetsService.Current.RenderStyles(false)
}
@@ -84,9 +84,8 @@
<Reference Include="Sitecore.Kernel, Version=11.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\..\..\packages\Sitecore.Kernel.NoReferences.9.0.171219\lib\NET462\Sitecore.Kernel.dll</HintPath>
</Reference>
<Reference Include="Sitecore.Mvc, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\lib\Sitecore\Sitecore.Mvc.dll</HintPath>
<Reference Include="Sitecore.Mvc, Version=2.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\..\..\packages\Sitecore.Mvc.NoReferences.9.0.171219\lib\NET462\Sitecore.Mvc.dll</HintPath>
</Reference>
<Reference Include="Sitecore.Mvc.Analytics, Version=11.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\..\..\packages\Sitecore.Mvc.Analytics.NoReferences.9.0.171219\lib\NET462\Sitecore.Mvc.Analytics.dll</HintPath>
@@ -1,47 +1,55 @@
@using Sitecore.Foundation.Assets
@using Sitecore.Foundation.Assets.Models
@using Sitecore.Foundation.Assets.Services
@using Sitecore.Foundation.SitecoreExtensions.Extensions
@using Sitecore.Mvc.Analytics.Extensions
@inherits WebViewPage
@{
Layout = null;
}
<!DOCTYPE html>
<!--[if IE 9]><html lang="en" class="ie9 no-js"><![endif]-->
<!--[if !IE]><!-->
<html lang="@Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
@if (!Sitecore.Context.PageMode.IsExperienceEditor)
{
@Html.Sitecore().Placeholder("head")
}
<!-- Latest compiled and minified JavaScript -->
@RenderAssetsService.Current.RenderScript(ScriptLocation.Head)
@RenderAssetsService.Current.RenderStyles()
@Html.Sitecore().VisitorIdentification()
</head>
<body class="header-static @(Sitecore.Context.PageMode.IsNormal ? "" : (Sitecore.Context.PageMode.IsExperienceEditor ? "pagemode-edit" : "pagemode-preview"))">
<div id="main-container">
<header class="header-static">
@Html.Sitecore().Placeholder("header-top")
@Html.Sitecore().Placeholder("navbar")
</header>
<main role="main">
@Html.Sitecore().Placeholder("page-layout")
</main>
<footer class="bg-dark">
@Html.Sitecore().Placeholder("footer")
</footer>
@Html.Sitecore().Placeholder("page-sidebar")
</div>
@RenderAssetsService.Current.RenderScript(ScriptLocation.Body)
</body>
@using Sitecore.Foundation.Assets
@using Sitecore.Foundation.Assets.Models
@using Sitecore.Foundation.Assets.Services
@using Sitecore.Foundation.SitecoreExtensions.Extensions
@using Sitecore.Mvc.Analytics.Extensions
@inherits WebViewPage
@{
Layout = null;
string cacheKey = RenderAssetsService.GetPageKey(Request);
}
<!DOCTYPE html>
<!--[if IE 9]><html lang="en" class="ie9 no-js"><![endif]-->
<!--[if !IE]><!-->
<html lang="@Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
@if (!Sitecore.Context.PageMode.IsExperienceEditor)
{
@Html.Sitecore().Placeholder("head")
}
@*Inline Styles Rendering*@
@Html.Sitecore().CachedRendering("{B14DA82E-F844-4945-8F31-4577A52861E1}", new RenderingCachingSettings { Cacheable = true, CacheKey = cacheKey + "_critical_styles" })
@Html.Sitecore().VisitorIdentification()
</head>
<body class="header-static @(Sitecore.Context.PageMode.IsNormal ? "" : (Sitecore.Context.PageMode.IsExperienceEditor ? "pagemode-edit" : "pagemode-preview"))">
<div id="main-container">
<header class="header-static">
@Html.Sitecore().Placeholder("header-top")
@Html.Sitecore().Placeholder("navbar")
</header>
<main role="main">
@Html.Sitecore().Placeholder("page-layout")
</main>
<footer class="bg-dark">
@Html.Sitecore().Placeholder("footer")
</footer>
@Html.Sitecore().Placeholder("page-sidebar")
</div>
@*Styles Rendering Deferred Styles *@
@Html.Sitecore().CachedRendering("{F04C562A-CBF9-40CF-8CA9-8CE83FDF0BFA}", new RenderingCachingSettings { Cacheable = true, CacheKey = cacheKey + "_bottom_styles" })
@*Scripts Legacy Jquery jquery-3.2.1 *@
@Html.Sitecore().CachedRendering("{B0DD36CE-EE4A-4D01-9986-7BEF114196DD}", new RenderingCachingSettings { Cacheable = true, CacheKey = cacheKey + "_bottom_scripts" })
</body>
</html>
@@ -17,6 +17,7 @@
<package id="Sitecore.Analytics.Model.NoReferences" version="9.0.171219" targetFramework="net462" developmentDependency="true" />
<package id="Sitecore.Analytics.NoReferences" version="9.0.171219" targetFramework="net462" developmentDependency="true" />
<package id="Sitecore.Kernel.NoReferences" version="9.0.171219" targetFramework="net462" developmentDependency="true" />
<package id="Sitecore.Mvc.NoReferences" version="9.0.171219" targetFramework="net462" developmentDependency="true" />
<package id="System.ComponentModel" version="4.0.1" targetFramework="net462" />
<package id="System.Diagnostics.Debug" version="4.0.11" targetFramework="net462" />
<package id="System.Globalization" version="4.0.11" targetFramework="net462" />

0 comments on commit df6f2e5

Please sign in to comment.