0 comments on “SXA Speedy – Supercharge your SXA Page Speed Scores in Google”

SXA Speedy – Supercharge your SXA Page Speed Scores in Google

We are excited to preview our latest Open Source module. Before jumping into the actual technical details here are some of the early results we are seeing against the Habitat SXA Demo.


Results:

Results

Before:

After

After:

Before
* Results based on Mobile Lighthouse Audit in chrome. 
* Results are based on a local developer machine. Production results usually incur an additional penalty due to network latency.

Want to know more about our latest open source SXA Sitecore module …. read on ….


I’m continually surprised by the number of new site launches that fail to implement Google recommendations for Page Speed. If you believe what Niel Patel has to say this score is vitally important to SEO and your search ranking. At Aceik it’s one of the key benchmarks we use to measure the projects we launch and the projects we inherit and have to fix.

The main issue is often a fairly low mobile score, desktop tends to be easier to cater for. In particular, pick out any SXA project that you know has launched recently and even with bundling properly turned on its unlikely to get over 70 / 100 (mobile score). The majority we tried came in somewhere around the 50 to 60 out 100 mark.

Getting that page score into the desired zone (which I would suggest is 90+) is not easy but here is a reasonable checklist to get close.

1) Introduce image lazy loading
2) Ensure a cache strategy is in place and verify its working.
3) Dianoga is your friend for image compression
4) Use responsive images (must serve up smaller images sizes for mobile)
5) Introduce Critical CSS and deferred CSS files
7) Javascript is not a page speed friend. Defer Defer Defer

The last two items are the main topics that I believe are the hardest to get right. These are the focus of our new module.

Critical_plus_defer

Check out the GitHub repository.

I have also done an installation and usage video.

So how will the module help you get critical and JS defer right?

Deferred Javascript Load

For Javascript, it uses a deferred loading technique mentioned here. I attempted a few different techniques before finding this blog and the script he provides (closer to the bottom of the article) seems to get the best results.  It essentially incorporates some clever tactics (as mentioned in the article) that defer script load without compromising load order.

I also added in one more technique that I have found useful and that is to use a cookie to detect a first or second-time visitor. Second-time visitors naturally will have all external resources cached locally, so we can, therefore, provide a completely different loading experience on the 2nd pass. It stands to reason that only on the very first-page load we need to provide a deferred experience.

Critical + Deferred CSS Load

For CSS we incorporated the Critical Viewport technique that has been recommended by Google for some time. This technique was mentioned in this previous blog post. Generating the Critical CSS is not something we want to be doing manually and there is an excellent gulp based package that does this for you.

It can require some intervention and tweaking of the Critical CSS once generated, but the Gulp scripts provided in the module do seek to address/automate this.

Our module has a button added into the Configure panel inside the Sitecore CMS. So Content Editors can trigger off the re-generation of the Critical CSS when ever needed.

Generate Critical button added to Configure.

Local vs Production Scores

It’s also important to remember that the scores you achieve via Lighthouse built into Chrome on localhost and your non-public development servers can be vastly different than production. In fact, it’s probably safest to assume that non-production boxes give false positives in the region of 10 to 20 points. So it’s best to assume that your score on production will be a little worse than expected.

Conclusion

It’s a fair statement that you can’t just install the module and expect Page Load to be perfect in under 10 minutes.  Achieving top Page Load Speed’s requires many technical things to work together. By ensuring that the previously mentioned checklists are done (Adequate Servers, Sitecore Cache, Image Loading techniques) you are partway over the line. By introducing the deferred load techniques in the module (as recommended by Google) you should then be a step closer to top score.

For more hints please see the Wiki on Github.

This module has been submitted to the Sitecore Marketplace and is awaiting approval.


Author: Thomas Tyack – Solutions Architect / Sitecore MVP 2019

0 comments on “Creating a custom SXA rendering with variants”

Creating a custom SXA rendering with variants

In this blog post we’ll step through the process of creating a custom SXA rendering with variants.  For this example, we’ll create a rendering that is used to display information about cars.  By using a rendering with variants, we can add a Car rendering to our page, and depending on which variation we choose, we can display it with a different appearance and different fields.  We’ll create a Car rendering with 3 variations:

  • Summary
  • Specifications
  • Full Details

Template

The first thing we need to do is create the template.  Even though some of the variations only display some of the fields, the template will have all of the fields for a car, and the variations will use only the fields they need.

Template

This template was created in /sitecore/templates/Feature/Cars/Car.

Rendering

The next step is to create the rendering.  Ours was created at /sitecore/layout/Renderings/Feature/Cars/Car.  The rendering should be a Controller Rendering.  Set the Controller (this one has been set to “Car”), and set the Controller Action to “Index”.  Set the Datasource Template to be the template we’ve just created (in this case, /sitecore/templates/Feature/Cars/Car), and the Datasource Location to “query:$site/*[@@name=’Data’]/|*[@@templatename=’Car’]”.  It’s important to set “Editable” to true so that the rendering will be available in the Toolbox.

Rendering

To make the rendering appear in the toolbox, we need to add it to Available Renderings.  The Available Renderings folder is  found under the Presentation folder of your SXA site.  First add an Available Renderings item under the Available Renderings folder.  In this case, I’ve added one called Cars.  Once you’ve added the Available Renderings item, click “Edit” on the Renderings field, and add your new rendering (“Car”) to the list of renderings.

AvailableRenderings

It doesn’t really matter what you call the Available Renderings item, or which Available Renderings item our rendering is added to, because the Available Renderings item is simply for filtering/organising the rendering in the content tree.  It doesn’t actually determine where it appears in the Toolbox.  The folder structure of where the rendering is located determines this.  For example, because this rendering is at /sitecore/layout/Renderings/Feature/Cars/Car, it will appear in the Toolbox under a new category of “Cars”.

Toolbox

Rendering Variants

This is where we setup the 3 variations of the rendering.  To start off, create a new Variants item called “Car” under the Presentation/Rendering Variants folder of your SXA site. Under that item, create 3 Variant Definition items for each of the variants we need.

When the variants have been added, they can be selected from the Variant dropdown list in the Experience Editor:

ListVariants

Under each of the Variant Definitions, we need to insert the fields to be displayed.  The desired layout of these fields will determine how we add the fields.  The fields can be grouped into sections, and the order and hierarchy of the fields directly matches the order and hierarchy of the HTML elements that get rendered.  This, coupled with the “Css Class” field allows you to have full control over the layout and appearance of the variant.   The beauty of this is that once this initial setup has been done, you can add as many variants to this rendering as you like without having to write any more code at all.

When adding the fields, it is important that the value of the “Field name”  matches the name of the field in the template.

As an example, the Summary variant has been created using this following structure:

SummaryVariant

The Css Class for the Image field has been set to “col-xs-3”, and the Css Class for the Car Details section has been set to “col-xs-9”.  The Tags for all of these items are using the default of “div”.  This configuration translates to the following HTML:

<div class="component car">
   <div class="component-content">
      <div class="col-xs-3 field-image">
         <img style="margin:0;" src="/-/media/458B8369BE6D40489797D75DDA8BB79D.jpg?h=114&la=en&w=200&hash=641FD08747F050B6AF1779E77E5BF2C24AB2CEC0" alt="" width="200" height="114" />
      </div>
      <div class="col-xs-9">
         <div class="field-make">Holden</div>
         <div class="field-model">Commodore</div>
         <div class="field-year">2007</div>
      </div>
   </div>
</div>

And it looks like this:

SummaryVariantRendered

As an example, we can have a completely different look for the same rendering by selecting the Full Details variant, which has been setup like this:

FullDetailsVariant

And it ends up looking like this:

FullDetailsVariantRendered

There’s a great article that covers this in more detail at http://www.markvanaalst.com/sitecore-experience-accelerator/the-power-of-the-variants/

Code

This section covers the code that needs to be created in your solution.

First add a new Feature module to your solution, then add the following items:

IRepository

using Sitecore.XA.Foundation.RenderingVariants.Repositories;

namespace YourBusiness.Feature.Cars.Repositories
{
   public interface ICarRepository : IVariantsRepository
   {
   }
}

Repository

using YourBusiness.Feature.Cars.Modes;
using Sitecore.XA.Foundation.Mvc.Repositories.Base;
using Sitecore.XA.Foundation.RenderingVariants.Repositories;

namespace YourBusiness.Feature.Cars.Repositories
{
 public class CarRepository : VariantsRepository, ICarRepository
  {
     public override IRenderingModelBase GetModel()
     {
         CarModel model = new CarModel ();
         FillBaseProperties(model);
         return model;
     }
  }
}

Model

No need to add our template fields in this instance

using Sitecore.XA.Foundation.Variants.Abstractions.Models;

namespace YourBusiness.Feature.Cars.Models
{
   public class CarModel : VariantsRenderingModel
   {
   }
}

Controller

Keep in mind that the controller must inherit from Sitecore.XA.Foundation.Mvc.Controllers.StandardController.  The Standard controller will handle the routing with default action result “Index”, so there’s no need to add our own, although we can override “Index” if we need to.

using YourBusiness.Feature.Cars.Repositories;
using Sitecore.XA.Foundation.Mvc.Controllers;
using Sitecore.XA.Foundation.RenderingVarients.Repositories;

namespace YourBusiness.Feature.Cars.Controllers
{
   public class CarController: StandardController
   {
       protected ICarRepository CarRespository
       {   get; set;   }

       protected IVariantsRepository VariantsRespository
       {   get;  set;  }

       public CarController(ICarRepository, carRepository, IVariantsRepository variantsRepository)
       {
           this.CarRespository = carRepository;
           this.VariantsRespository = variantsRepository;
       }

       protected object GetVariantsModel()
       {
           return VariantsRespository.GetModel();
       }

       protected override object GetModel()
       {
          return CarRepository.GetModel();
       }
   }
}

View

It is important that all SXA components should be wrapped in “component” and “component-content” divs. “Model.Attributes” adds styles from the rendering parameters.

@model YourBusiness.Feature.Cars.Models.CarModel

@if (Model.DataSourceItem != null || Html.Sxa().IsEdit)
{
<div>
   <div class="component-content">
      @if (Model.DataSourceItem == null) 
      { 
         @Model.MessageIsEmpty 
      } 
      else 
      { 
         foreach (VariantFieldBase variantField in Model.VariantFields) 
         { 
            @Html.RenderingVariants().RenderVariant(variantField, Model.Item, Model.RenderingWebEditingParams) 
         } 
      }
   </div>
</div>
}

Config

<?xml version="1.0" encoding="utf-8"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
    <sitecore>
        <services>
            <configurator type="YourBusiness.Feature.Cars.Pipelines.RegisterCarServices, YourBusiness.Feature.Cars" />
        </services>
    </sitecore>
</configuration>

]

Pipeline

Here we register the dependencies.

using Microsoft.Extensions.DependencyInjection;
using YourBusiness.Feature.Cars.Repositories;
using Sitecore.DependencyInjection;
using Sitecore.XA.Foundation.RenderingVariants.Repositories;

namespace YourBusiness.Feature.Cars.Pipelines
{
   public class RegisterCarServices : IServicesConfigurator
   {
      public void Configure(IServiceCollection serviceCollection)
      {
         serviceCollection.AddTransient<ICarRepository, CarRepository>();
         serviceCollection.AddTransient<IVariantRepository, VariantRepository>();
      }
   }
}

 

0 comments on “SXA Installation Pitfalls”

SXA Installation Pitfalls

When installing SXA on a fresh Sitecore instance, things will generally go pretty smoothly, however, when installing SXA on an existing Sitecore instance with customisations, it’s not necessarily quite so simple.  Here’s a summary of some of the issues that were encountered when recently installing SXA 1.4 onto a Sitecore 8.2.4 instance.  Hopefully this post will help if you encounter similar issues.

Dependency Injection

In this instance, there was code that was registering dependencies using wildcards.  Specifically, it was adding (among others) assemblies matching the pattern “*.Feature.*”.  This was wrongly picking up SXA assemblies and was giving errors in the Experience Editor like:

Error Rendering Controller: BrowserTitle. Action: Index: Could not create controller: 'BrowserTitle'.

To fix this, the Dependency Injection code was altered to exclude all assemblies matching the pattern “*.XA.*”.

Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll

The Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll file packaged in SXA 1.4 is an older version than what is being used throughout the solution we’re updating, so when trying to install the package, the installation failed halfway through. To fix this, the SXA install package was altered using 7-zip to replace the included DLL with the newer version.

Missing Rendering IDs (no null check)

This issue may be specific to this instance, and might be due to invalid data, but it’s worth mentioning, since SXA is not doing a null check and this problem may crop up for you, too.

When viewing a particular page, the following exception was thrown:

Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
Source: Sitecore.XA.Feature.Composites
at Sitecore.XA.Feature.Composites.Pipelines.GetXmlBasedLayoutDefinition.InjectCompositeComponents.GetCompositeComponents(XElement layoutXml)
at Sitecore.XA.Feature.Composites.Pipelines.GetXmlBasedLayoutDefinition.InjectCompositeComponents.Process(GetXmlBasedLayoutDefinitionArgs args)

This turned out to be some renderings that had no ID, and SXA wasn’t doing a null check. The specific xmlLayout is shown below:


Editing the raw values and removing the renderings with a null ID fixes this problem.

To check if there were any other pages with this same problem, a small powershell script was written:

$items = Get-ChildItem -Path "master:/sitecore/content/Consumer/Home" -Recurse
foreach($item in $items) {
$renderings = Get-Rendering -Item $item
foreach($rendering in $renderings) {
if($rendering.ItemID -eq $null) {
Write-Host Item: $item.DisplayName $item.ID
}
}
}

Media Library/Project Folder

The SXA installation wants to create its own “Media Library/Project” folder, using a specific ID. If this item with the specific ID doesn’t exist, SXA will fail when creating a Tenant or Site.   Your instance may already have a folder by this name, in which case it will need to be renamed before the SXA installation, then it’s contents moved into the folder created by SXA.

Duplicate Navigation Controllers

For this instance, when adding the SXA navigation rendering to a page, the following exception occurs:

Multiple types were found that match the controller named 'Navigation'. This can happen if the route that services this request ('{*pathInfo}') does not specify namespaces to search for a controller that matches the request.

There may be other similar controllers in your instance where you get the same problem.