Website Accessibility Tricks & Tips

Article Pre-Evaluation:

Estimated read-time: 14 Minutes

Level of reading competence and understanding: Semi-Technical

Author: Gavin McQuienn, Lead Front-End Engineer, Aceik


What we cover in this article:


What is Website Accessibility?

Website accessibility is the inclusive practice of structuring a website to ensure that the maximum number of people can access/navigate and obtain information within websites on the World Wide Web, in particular for those with physical disabilities & situational disabilities, such as socio-economic restrictions on bandwidth and speed.

In technical-speak, it is the practice of implementing/leveraging the proper usage functionally-descriptive HTML tags, best practices-practice HTML structures, CSS, images and media, such as video and audio.

Accessibility Users – Web Statistics & Debunking the Myths 

In the past, there has often been a mindset that users utilising disability related accessibility website features were the minority. Well here are a few things that most do not consider when casting thought upon this subject.

Accessibility – not only benefits people with disabilities 

Business Cases for Accessibility Improvements

  • Legal & General Group – doubled visitor numbers, cut maintenance costs by two thirds and increased natural search traffic by 50%. 
  • Tesco – £35 thousand GBP to build their accessible website, £13 million GBP per year in resultant revenue. 
  • CNET – 30% increase in traffic from Google after CNET started providing transcripts, “We saw a significant increase in SEO referrals when we launched an HTML version of our site, the major component of which was our transcripts.” – Justin Eckhouse, CNET, 2009.
  • This American Life is a broadcast heard on more than 500 National Public Radio (NPR) stations by about 2.1 million listeners each week in the United States. In 2011, the broadcaster committed to creating transcripts for their entire archive of recorded programs and recorded. This subsequently resulted in:
    • search traffic increased 6.86%,
    • better comprehension for visitors who use English as a second language,
    • visitors were able to use transcripts in noisy or sound-sensitive environments,
    • ability to more easily translate, and
    • ability to search text to reference a specific section of audio.
  • “Many organisations are waking up to the fact that embracing accessibility leads to multiple benefits – reducing legal risks, strengthening brand presence, improving customer experience and colleague productivity.” – Paul Smyth, Head of Digital Accessibility, Barclays

Accessibility Internet Traffic Statistics 

In the USA ~ according to the Census Bureau on July 25, 2012:

  • 54% of adults living with a disability go online.
  • 56.7 million Americans (18.7% of the population), that is a figure of 19.9 million (roughly 8.2%) have proven to have difficulty lifting or grasping objects, which could impair their ability to use a mouse or keyboard.
  • 8.1 million (3.3%) suffer from vision impairment. Such demographics commonly use tools such as a screen magnifier, screen readers, or might have a form of color blindness, to which colour contrasts become ever so important.
  • 7.6 million (3.1%) have been proven to have a hearing impairment – given such disabilities would rely heavily on transcripts and/or captions for audio/video media.
  • Sight and hearing impairments cover an average of 6.8 percent of the population aged 15 years +. These figures jump to a whopping 21.3 percent of the population when you look specifically at the ageing population, people aged 65+.
  • The Baby Boomer generation (born between 1945 and 1964) is going to cross that 65-year barrier in 2010. This same web-savvy generation created the Internet, for the most part and represents one of the largest single demographics in the United States.

What can you do to increase your website’s accessibility?

Implementing accessibility features has been proven to not only increase the overall user experience and usability of a website, which will ultimately translate into higher traffic and increased SEO impact / reach, but will ensure modern best-practice standards are adhered to, which ultimately instills a higher level of code and content quality throughout a site. 

There are many things that you can start doing today, but to successfully administer a high level of accessibility is generally a 3-pronged approach:

  1. Design considerations
    1. Ensuring that even at the initial design phase that colour-contrasts, disability user-journey/navigation & audio/video media content alternatives are considered
  2. Content editors preparation, structures, awareness and consideration 
    1. Preparing audio/video media and written content for multiple demographics, such as transcripted media, listing average article read-time estimations, competency reading level grading & text alternatives for media including images, video and audio
  3. Adopting technical development hygiene / strategies 
    1. Making use of the correct usage and structured HTML, such as tab-indexed links/navigation items, hidden content for screen-readers, and especially accessibility related HTML tags & CSS, such as Aria labels, CSS user-interaction related Pseudo classes. 

Accessibility – Technical Standards, approaches, best practices & things to consider.

We have separated some well-known strategies into categories of implementation-difficulty and ultimately, development/preparation related costs/efforts ~ it must be noted that some of these tactics can be implemented to existing codebases in a, ‘moving forward’ mentality / approach, which will still slowly start to increase your accessibility support.

This may include, but is not limited to such items as:

Low Cost / Effort / Preliminary planning required
Implementing correct usage of functionally user-interactive CSS Pseudo-Classes such Focus, Active, Visited, Hover, etc

.btn {
  &:hover,
  &:focus,
  &.focus {
    color: $purple5;
    background-color: darken($yellow1, 10%);
  }
}
  • Meaningfully named, underlined/colored (or otherwise differentiated) Anchor links
  • Textual equivalents provided for images
  • Providing meaningful `alt` & `title` tags for all imagery
<img src="" alt="ENTER IMAGE DESCRIPTION - Helpful with SEO" title="This is an image of a Ragdoll cat jumping">

`Tab-indexed` user journey-tested Anchor Links and Buttons, as well as `title` tags explaining functionality 

<a class="btn btn-secondary" href="#" tabindex="0" title="Click here to see cats from category 1">
Pictures of category 1 cats
</a>
<a class="btn btn-secondary" href="#"  tabindex="1" title="Click here to see cats from category 2">
Pictures of category 2 cats
</a>
<a class="btn btn-secondary" href="#"  tabindex="2" title="Click here to see cats from category 3">
Pictures of category 3 cats
</a>

Medium Cost / Effort / Preliminary planning required

  • Text and images are large and/or enlargeable
  • Mobile optimised imagery, media & mobile-specific layouts 
  • Textual equivalents provided for images 
  • Text and images are large and/or enlargeable

High Cost / Effort / Preliminary planning required

  • Keyboard supported Menu-Navigations
  • Magnifying text/imagery options for content
  • Alternate methods of obtaining information regarding visual/audio media, such as  closed captioned and/or a sign language versions
  • Captha’s that have multiple options to human validity, such as Audio options regarding successful passphrases, or modern captchas do not require input from a user


  • Print-friendly web pages – making sure that your pages are accessible and usable even when printed or saved as a PDF file

Aria Label HTML Tags & Screen Reader Specific CSS Classes 

What are Aria Labels HTML related Tags?

ARIA stands for Accessible Rich Internet Applications and is a set of attributes that define/provide alternatives to make web applications / content (in particular those written using Javascript) more accessible to people with disabilities.

Aria Labels extend HTML and pass information to assistive technologies related to interactions and widgets commonly used in applications, which provide the user with additional information that would not otherwise be accessible. For example, ARIA enables accessible navigation landmarks in HTML4, form hints and error messages, live content updates, JavaScript related widgets and many more. 

Luckily HTML5  provides a lot more descriptive HTML tags, which are designed to provide additional information to the end user regarding the type of element they are viewing, while enabling more descriptive code which enables developers to more easily decipher new code block/snippets, which in turn increases productivity and the efficiency one can alter existing components. 

Here’s the markup for a progress bar widget: ~ snippet taken from Developer.Moziila

<div id="percent-loaded" role="progressbar" aria-valuenow="75"
    aria-valuemin="0" aria-valuemax="100">
</div>

Here we have a progress bar and it is built using a `<div>`, which actually gives the user no meaning. Currently HTML5 has new inbuilt tags that allow you to break up your elements with more meaning, but unfortunately, a lot of the time there isn’t a more semantic tag available for developers to use HTML4 or 5, so we need to include ARIA roles and properties. 

In this example, we are adding specified attributes to the element such as the `role=”progressbar”` attribute, which notifies the browser that this element is a Javascript driven progress bar widget. The `aria-valuemin` and `aria-valuemax` attributes specify the minimum and maximum values of the element, and the `aria-valuenow` expresses the current state of the progress but, so this must be kept in sync with the JavaScript.

Screen Reader Specific CSS Classes

There are occasional instances where content should be made available to screen reader users, but hidden from sighted users. In the vast majority cases, content that is available visually should be available to screen reader users, and vice versa. Cases where verbose cues or instructions are provided only for screen reader users are most likely a reflection of poor design, usability, and accessibility. However, there are a few cases where information or meaning is apparent visually, but may not be apparent to screen reader users. In these rare cases, it may be appropriate to cause content to be read by a screen reader, but remain invisible to sighted users.

Techniques for hiding content 

There are several mechanisms that can be used for hiding content. It’s important that a technique be implemented that results in the desired outcome and accessibility.

/* Text meant only for screen readers. */
.screen-reader-text {
  border: 0;
  clip: rect(1px, 1px, 1px, 1px);
  clip-path: inset(50%);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
  word-wrap: normal !important;
}

Here is a few approaches of embedding additional information for the user to utilise

  • `display:none` or `visibility: hidden`
display:none;
// or
visibility: hidden;
  • hidden attribute
<p hidden></p>
  • `width:0px`, `height:0px` or other 0 pixel sizing technique
width: 0px;
height: 0px;
  • `text-indent: -10000px;`
text-indent: -10000px;
  • Absolutely positioning content off-screen
.sr-only {
  position:absolute;
  left:-10000px;
  top:auto;
  width:1px;
  height:1px;
  overflow:hidden;
}
  • The `.sr-only` CSS class, which stands for  “screen reader only”, is just an abrtiory name and can be called anything you wish, but whatever you name this should then be referenced from within the tag of the element being hidden, as shown:
<div class="sr-only">This text is hidden.</div>

For more information regarding these techniques, please visit WebAim.org

Resources for Online Accessibility Audits

The following is a list of websites and web tools that are built to help you plan, design and also evaluate any accessibility flaws that may have been overlooked in the development of your current site. 

Most of these tools are free (at an entry-level anyway) and if nothing else can evaluate and provide feedback into any website that is currently live on the internet and include tools that can help evaluate colour contrasts, HTML structures / markup that could be improved to ensure small, and sometimes large wins in regards to increasing accessibility compliance.

There are many tools and services available at www.w3.org/WAI/ER/tools, but a lot are actually links to businesses trying to entice you to let them assess & implement your accessibility upgrade, so finding the hidden-gems that are free can be a little painstaking. So here is shortlist we recommend:

Accessibility Evaluation / Compliance tools & helpers: 

Best Practice Examples of Accessible Websites

Here, in no particular order are some examples of websites that meet a high accessibility standard and still look modern, fun and/or are highly functional: 

Based on what you’ve just read above, take a look at these websites and let us know what accessibility features you can find. Post a comment below or reply back to info@aceik.com.au

Technical Legalities around Accessibility

More and more cases are starting to surface regarding end-users suing companies for negligence in regards to not adhering to Accessibility compliance, which means your organisation’s website could be at risk without you realising it. The reality here is, you are not alone.  

Here are some related statistics regarding Accessibility Laws and also some examples of what has happened in the past when an end-user of these websites decides to take these companies to court, in regards to failure to comply with these laws and the needs of individuals with disabilities.

Some surprising statistics regarding Accessibility Law

  • In the UK alone, on average 70% of websites are not compliant with accessibility laws. Globally, around 10% of the world’s population (650 million people) live with a disability. As life expectancy increases, this number is also expected to grow.
  • 92% of the most popular federal websites fail to meet basic standards for accessibility, says a study from the Information Technology and Innovation Foundation

Accessibility related Legal Case Studies in the US

  • In January 2019, Beyoncé Knowles’ company, Parkwood Entertainment, became the defendant in a class-action lawsuit alleging that it violated the Americans with Disabilities Act (ADA). The suit, filed by a blind woman from New York, claimed that the company’s website, Beyonce.com, did not provide accommodation for people with significant vision impairments, leaving an estimated 2 million blind people and others with vision impairments unable to access the primary portal for news about all things Bey.
  • A blind man filed a lawsuit against Domino’s in September 2016 and claimed that he was unable to order customized pizza or take advantage of online-only discounts because both the website and mobile app wouldn’t work with his screen reading software. Neither the website or app met basic Web Content Accessibility Guidelines (WCAG) and a judge ruled in favor of Guillermo Robles, the man who filed the lawsuit.
  • A class action lawsuit was filed in January 2018 against Burger King by a visually-impaired woman. The individuals involved were using screen reading software to understand and interact with the website. Because there were no alt-tags or other features in place, the individuals reached significant barriers in accessing basic information on the website.

Accessibility related Legal Case Studies in Australia

  • Coles.com.au – Closer to home, a case originated in early November 2014 where coles.com.au was sued by disability-user who claimed that she was being discriminated against in regards to being able to access the website ~ Please follow these related article links: Coles lawsuit Article 1, Coles lawsuit Article 2
  • 2000 Sydney Olympics – On the 7th June 1999, The Maguire Law Firm made a complaint to the Human Rights & Equal Opportunity Commission (HREOC), alleging that the Sydney Organising Committee for the Olympic Games (SOCOG) had discriminated against him as a disbled person, in contravention of the Disability Discrimination Act 1992 in three aspects: 
    • The failure to provide braille copies of the information required to order Olympic Games tickets
    • The failure to provide braille copies of the Olympic Games souvenir programme, and
    • The failure to provide a website which was accessible to Maguire

After the completion of the ticket book case (Maguire v SOCOG 1999 ) on 30 September 1999, conciliation on the remaining matters was attempted but by 29 November 1999, the talks failed. ~ This information taken from Wikipedia

Aceik – Current Accessibility Examples 

We thought it best to highlight a couple of examples from our current clientele that highlight some great development-integration accessibility pieces that we have had the honour of implementing of late:

  • The City of Yarra Council – https://www.yarracity.vic.gov.au/
    • Including features such as a fully keyboard function navigation, the ability to increase website text-sizes, print-friendly page options have been included, multi-language selection abilities, clearly highlighted link focus states and whole range other accessible consideration can be found throughout this website.
  • Chisholm Institute of Tafehttps://www.chisholm.edu.au/
    • Once again the navigation here is completely keyboard accessible, link focus and hover-states are clearly highlighted, colour contrasts have been carefully  considered, images are clearly labelled and media accessibility has also been considered, this allowing users multiple methods to access non-written media.

Personal notes from the author

In closing, personally I have researched this topic for years, and to my knowledge no one document or article pulls together all related facets (and so extensively) on this subject matter as I have attempted to do here, hence why I have made this quite a lengthy piece. 

It really is a massive topic to cover and there are so many angles one needs to consider to gain a holistic understanding that will empower/compel business-owners and stakeholders to justify the additional effort, cost and benefits associated with implementing extensive and well planned Web-Accessibility, so I hope this helps to empower not only business owners, but also educates and increases the level of Website Development standards, industry wide.

Article Resources

JSS and OKTA: Blog 2 – Login via embedded OKTA Form (August RELEASE)

This blog post is based on the OKTA samples @ https://developer.okta.com/quickstart-fragments/angular/default-example/ and the OKTA sign in widget that can be integrated into the page.

The branch mentioned above contains a working example that I will now run through in the rest of this blog. Once up and running your should get a login embedded into our JSS application that allows us to login via OKTA.


Overview

Firstly lets have a quick run through of the changes we made to the first blog in order to integrate the widget.

  1. OKTA configuration settings
    • These are stored in a settings file in the root of the JSS application: jss-okta-config.json
    • All settings to do with our OKTA instance can be added in here.
  2. Create the placeholder component to contain the widget
    • In JSS we scaffold up a new component
    • src\app\components\okta-sign-in\okta-sign-in.component.ts
    • Have a look at https://github.com/TomTyack/jssokta/blob/feature/okta-sign-in-widget/JSS/src/app/components/okta-sign-in/okta-sign-in.component.ts
      1. ngOnInit()
        1. Note how the code dynamically imports the OKTA sign in widget.
        • import('@okta/okta-signin-widget')
        • This is necessary as the library contains a reference to window. Which will break our Server Side code if imported normaly.
        • So in order to workaround this flaw we dynamically import the library only after verifying that this code is running client side.
      2. detectTranslationLoading()
        • Wait for the dictionary service to be loaded so that we can inject the Dictionary into the form.
      3. bootupSignin()
        • Initialise the OKTA widget configuration, inject labels and URLS
      4. injectWidgetPhase()
        • Render the widget
    • This contains the widget code and the has a matching from end HTML template in Angular.
      • The HTML file contains the following important tag
      •  <div id=”okta-signin-container”></div>
  3. Add the component to the /login route
  4. Adjust the navigation to include a new button for the widget
  5. Dictionary additions

Demo Video

To show you a video of this JSS example in action take a quick gander at the following video:


Demo Installation

  1. Clone the Repository
  2. Deploy the application. Follow the same instructions from the first blog. <<< UPDATE LINK
  3. Run the application. Follow the same instructions from the first blog. <<< UPDATE LINK
  1. Click on the “Login Embedded” link in the navigation
  2. Login to OKTA (if not already) using the details you registered with.
  3. You should arrive back on the profile page
  4. undefined
  5. Success!! hopefully 🙂
  6. Inside the OKTA Dashboard is a handy log that shows all login activity. This is a great way to see what is going on. Screenshot shown at the bottom.
    • undefined

Summary

That concludes the run through of how to integrate the OKTA Angular SDK and Embedded Widget into Sitecore JSS. OKTA is a leader in user authentication management and having the ability to integrate into our JSS applications is an exciting prospect. I hope this example is of use to you and your teams if your considering the same technology mix.


JSS and OKTA: Blog 1 – Login via External OKTA Form

This blog post is based on the OKTA samples @ https://developer.okta.com/quickstart-fragments/angular/default-example/

The OKTA samples makes use of the OKTA Angular SDK and allows you to set up a development OKTA cloud instance for testing the code.

For this blog I have integrated the OKTA example into the Angular JSS starter repository to for a new repository to accompany this blog. https://github.com/TomTyack/jssokta

This repository contains a working example that I will now run through in the rest of this blog. All you need to do is sign up for your own developer sandbox (OKTA) instance using a dummy user and test it out.


Overview

Firstly lets have a quick run through of the changes we made to the original examples in order to integrate them with the angular JSS application.

  1. OKTA configuration settings
  2. Provide the Login and Logout Buttons
  3. Create the Callback Handler
    • The callback handles integration in JSS takes place inside: src\app\routing\routing.module.ts
    • JSS Example: https://github.com/TomTyack/jssokta/blob/master/JSS/src/app/routing/routing.module.ts
    • In this case I made the route: /implicitcallback
    • Importantly the route must be added at the top of the list so that JSS routing doesn’t hijack the route before our OKTA module gets a chance. I spent a little while scratching my head over this one when I originally added it the bottom of the route config.
  4. Update your NgModule
    • This requires a little bit of adjustment from the original example.
    • Module integration is done via: src\app\app.module.ts
  5. Use the Access Token

Demo Video

To show you a video of this JSS example in action take a quick gander at the following video:

Note: In the video I started off the demo by running in Disconnected mode with localhost. Surprisingly this worked and it redirected back to the connected app domain. In reality a better test would have been to start on the same domain in integrated mode. I’m not sure that you could run this test end to end in disconnected.

Demo Installation

  1. Clone the Repository
  2. Sign up for an OKTA developer account
    • https://developer.okta.com/signup/
    • When it asks you what sort of application you want just click “Do this later”.
    • Confirm your email address and fill out the security questions and change your temporary password.
  3. In the top navigation withing the OKTA Dashboard
  4. Back in the JSS OKTA Repository (open it in VS Code or your editor of choice)
    • From the command line run: npm install
    • Open the file: jss-okta-config.json (in the root of the JSS Application)
      • issuer: Swtich out “INSERT-OKTA-ID” with the relevant ID from the same domain your viewing the OKTA portal in.
      • redirectUri: Replace ‘jssokta’ with ‘jss.okta.portal’ or whichever domain you set.
      • clientId: Found on the application > General tab. About 20 characters long.
  5. IIS
    • OKTA requires us to be running a domain with https, as such it makes it difficult to test this out in Disconnected mode.
    • Setup a Sitecore instance and make sure JSS is installed.
    • Add your new domain to the local hosts file and make sure its mapped to 127.0.0.1
    • Add the new domain to your Sitecore instance in IIS and make sure it capable of HTTPS. Use the developer certificate as a default.
  6. Back in the JSS OKTA Repository
    • Got to sitecore\config\JSSOkta.config
      • hostName: jss.okta.portal
    • From the command line run: JSS Deploy app
      • run through the setup as you would any JSS application so that it would connect with your Sitecore instance.
      • Sample config from my tests: See scjssconfig.json at the bottom of this blog
    • From the command line run: JSS Deploy config
    • From the command line run (again): JSS Deploy app -c -d
  7. Test out the deployed application:
    • Navigate to your domain: example: https://jss.okta.portal/ (must have SSL)
    • If prompted about the SSL security warning proceed and ignore. “Proceed to jss.okta.portal (unsafe)”
    • undefined
    • Click on the “Login” link in the navigation
    • Login to OKTA (if not already) using the details you registered with.
    • You should arrive back on the profile page
    • undefined
    • Success!! hopefully 🙂
    • Inside the OKTA Dashboard is a handy log that shows all login activity. This is a great way to see what is going on. Screenshot shown at the bottom.
      • undefined

Summary

That concludes the run through of how to integrating the OKTA Angular SDK in Sitecore JSS. OKTA is a leader in user authentication management and having the ability to integrate into our JSS applications is an exciting prospect. I hope this example is of use to you and your teams if your considering the same technology mix.


OKTA Setup Screenshots and Sample Config

I have included screenshots of all my OKTA settings below. As I know this can be difficult to diagnose at times.


scjssconfig.json

{
  "sitecore": {
    "instancePath": "C:\\inetpub\\wwwroot\\test.dev.local",
    "apiKey": "{FB95B118-E04F-4D5B-9465-01AE804A2F5A}",
    "deploySecret": "r6bnvuhv13beudhix1lxnej2ci38u0i6kxhnpy22i6ps",
    "deployUrl": "http://jss.okta.portal/sitecore/api/jss/import",
    "layoutServiceHost": "https://jss.okta.portal"
  }
}

Introduce YML Linting to your JSS Apps

Intro: This post shares how and why you might like to introduce a YML linter into the build process for your next Sitecore JSS project. Particularly if you are relying on the YML import process when building a new application. Shout out to David Huby (Solutions Architect) for introducing team Aceik to yaml-lint.

Why would you want to do this on a JSS project?

When running the JSS application and testing latest changes, we sometimes discovered some strange behaviour with dictionary items, or a page might not load properly.

A 404 page displayed after an invalid YML change was made

This can be caused by a small (incorrect) change in YML breaking individual routes. For example, lets say you have an incorrect tab or character in the wrong place. The YML syntax requires correct spacing and line returns to be valid but this is not always so obvious when done incorrectly. Sometimes only after you run the JSS application and test out the changes do you discover some strange behaviours or the page not loading properly.

To avoid this we found it handy to introduce a YML linter into the JSS build process. This solves the issue of someone making a small change to the YML files and breaking individual routes.

Here are the steps needed to introduce a YML linter into a node-based JSS project:

  1. Install yaml-lint (https://www.npmjs.com/package/yaml-lint)
  2. In the application root create the file .yaml-lint.json
  3. Update the package.json
    • Create a new script entry called yamllint
      • “yamllint”: “node ./scripts/yaml-lint.js”
    • Update the script called ‘build’
      • “build”: “npm-run-all yamllint –serial bootstrap:connected build:client build:server”,
  4. Download the following scripts file and place it in the /scripts folder
    1. https://github.com/TomTyack/jss/blob/feature/YAML-Linter/samples/react/scripts/yaml-lint.js

You can also see the pull request with the above changes at:

https://github.com/Sitecore/jss/pull/385/files

Demo

One Performance Blog to Rule them all – Combining the 6 Pillars of Speed

I have done a number of posts and talks at user groups on Page Speed and performance over the last few years. I have split the various topics into individual blog posts for the most part as performance is dependent on many factors. What has really been missing is a complete demo of how all the different techniques come together to give your site a really good score. So that’s what I intend to demo here is the combination of the 6 pillars of page speed in one Sitecore instance. To recap here are the 6 pillars of page speed performance in my opinion:

1) Introduce image lazy loading

2) Ensure a cache strategy is in place and verify its working. (must have adequately sized production servers)

3) Deploy image compression techniques

4) Use responsive images (must serve up smaller images sizes for mobile)

5) Introduce Critical CSS and deferred CSS files

6) Javascript is not a page speed friend. Defer Defer Defer

I have shown a subset of these previously but crucially three critical pillars to do with imaging were hard to achieve at the time. This is now possible due to being able to support Next Gen image compression (webp), which I wrote about in my previous blog. With a little more time and investigation Image Lazy Loading, responsiveness and image compression to give a more complete picture of how each pillar impacts page speed.

Here are the tools and blogs I will use to achieve each of these:

1) Image Lazy Loading – Blog post by MVP Sitecore SAM and https://github.com/thinker3197/progressively

2) SXA Cache Settings – SXA official documentation

3) Next Image (WEBP) Image Compression – https://github.com/Aceik/ImageCompression

4) SXA Responsive Images – SXA official documentation

5) Introduce Critical CSS and deferred CSS files – https://github.com/Aceik/Sitecore-Speedy

6) Javascript is not a page speed friend. Defer Defer Defer – https://github.com/Aceik/Sitecore-Speedy

Alternatives: Mark Gibbons (MVP) recently upgraded the Dianoga image library to support WEBP. Worth a look if you don’t want to use a third party API. It also supports a CDN. Also Vincent Lui (MVP) also pointed out in his recent SUGCON talk, you can achieve both image compression and image lazy loading via some of the modern CDN’s. That is a great (easy) option if you are retro fitting these techniques to a live website.

I’m not going to dive deep into exactly how to setup each of these things as I think the individual links have sufficient instructions. I will show in the Demo videos how each pillar impacts the HTML rendered. For the most part I am keen to demonstrate the impact of each of these line items and how each one will benefit your page speed score.

Before we begin its important to understand that the algorithm (Lighthouse) behind Google’s Page Speed insight doesn’t work in an exactly linear fashion. If you improve your score by ticking off one of the above, don’t expect ticking off another issue will have the same benefit. The last 20 points out of 100 (on the mobile scoring system) is that hardest to achieve based on what I have seen.

Live Demo Video Series that accompanies this blog:


Test Outline:

Google Page Speed Insights — Scores can fluctuate widely based on network latency. At time you will experience score fluctuations at different times of the day on the same site.

In general this is a guide

Here is the general outline of the VM that hosted the IIS instance for testing. I also put the VM under some basic load while running the tests.

  • All the test below used Sitecore 9.3 and the SXA habitat example site.
  • Test used the live Google Page Speed insights tool via the url: https://developers.google.com/speed/pagespeed/insights/
  • Sitecore was setup on an Azure VM with the specifications:undefined
  • The test was run 5 times, to get an average score.
  • The test page was the homepage of the Habitat site and the page was requested before running the test 5 times so that the instance could be considered warm.
  • EXM and XDB were not running on these test instances.
  • Test results are Mobile Page Speed scores only – This is the most important metric in today environment and good desktop scores are not really a challenge.
  • The default Habitat cache rendering for Navigation was left on for all tests. (without this the site fails under basic load altogether)
  • All tests were conducted under load in an attempt to replicate a production environment. For this I used a node package called loadtest.
  • SXA CSS/Javascript optimisations were turned on, but as I have mentioned before this has a minimal performance boost.

loadtest -c 10 –rps 10 http://baselinecd.dev.local/

10 requests per second with a concurrency of 10

Baseline Score

The Baseline score encompasses the habitat site installed with no modifications.

Result: 48 / 38 / 40 / 34 / 38 = 39.6/100 Average

Observation: Heavily penalised for CSS and Javscript loading times.


Image Lazy Loading

All images on the homepage were converted to be Lazily loaded. A single large blurred image was used as the placeholder for all images.

Result: 57 / 55 / 61 / 52 / 63 = 57.6/100 Average

Observation: Around the mid point of the scale, image lazy loading has around a 15 – 20 point impact.


Rendering Cache Strategy

I have blogged extensively about this in the past but setting up cache settings properly is so critical and has a major impact. Its also one of the easiest things to fix for a poorly performing Sitecore site. Also note the only way to accurately demonstrate the impact that Rendering cache has on a site is to test it under load.

This test was run with higher user per second: loadtest -c 10 –rps 30 http://baselinecd.dev.local/

With Cache Enabled:

49 / 56 / 41 / 54 / 54 = 50.8

Without Cache Enabled:

ERR_TIMED_OUT / ERR_TIMED_OUT / ERR_TIMED_OUT / ERR_TIMED_OUT / ERR_TIMED_OUT = You get the point 🙂

Observation: Rendering cache settings are critical and should be the first step in Page Load Speed refinement for a Sitecore site. 10 Point benefit observed once a site is stable under load.


Image Compression

Result: 60 / 58 / 61 / 62 / 62 = 60.6/100 Average

Observation: Around the mid point of the scale, image lazy loading has around a 20 point impact.


Critical CSS

Result: 74 / 78 / 79 / 81 / 81 = 78.6/100 Average

Observation: The combination of critical CSS in the head and Deferred styles provides a meaningful page speed boost. 25 Point observed benefit.


Deferred Javascript

Result: 92 / 94 / 93 / 94 / 94 = 93.4/100 Average

Observation: Javascript has a massive impact, reducing it drastically in the initial payload provides massive page speed improvements. 40 Point observed benefit.

You might think, hey I will just do Deferred Javascript and it will be all good. While this particular PIllar/Criteria does have the biggest impact. Every site is different and as mentioned earlier scores fluctuate. The upper part of the scoring system is the hardest to reach. So while this is a great starting point, ignore the other speed pillars at your peril.


Responsive Images

Result: 56 / 54 / 59 / 56 / 60 = 57/100 Average

Observation: Around the mid point of the scale converting images to be responsive (srcset support) has about a 10 point impact.


Results Summary

CriteriaAverage ScoreObserved Benefit
No Change (SXA Habitat Home OOTB)41.8 / 100
Image Lazy Loading57.6 / 10015 Points
Sitecore Rendering/HTML Cache Settings50.8 / 10010 Points
Image Compression (webp)60.6 / 10020 Points
Critical CSS78.6 / 10025 Points
Deferred Javascript93.4 / 10040 Points
Responsive Images57 / 10010 Points

The Pillars Combined

In isolation we can see the rough results of what each of the pillars might do to our Page Speed. The real question is what does combining all these pillars produce.

Result: 100 / 100 / 100 / 100 / 100 = 100/100 Average

Observation: Do I expect this on an actual production site realistically ? That is certainly the dream, but in reality you should be over the moon if you make it into the 90s and pat your self on the back if you get into the 80s as well. For any Sitecore site if you make it into the 90’s for mobile, your doing an amazing job.

Admittedly for the combined demo I skipped the responsive image pillar. SXA supports Responsive Images but not in combination with data attributes. It was going to be a bunch of work to write a custom SXA handler to support both lazy loading and responsiveness at the same time. That is not to say its not possible. Either way the impact was minimal.

Conclusion

Page speed is so critical to SEO and visitor conversion. A slow site instantly turns away users on mobile and tablet devices. Admittedly the final result shown above and in the video have required that all the right tools be available to the Sitecore community. Which up until recently you likely needed to bake your own solutions in order to get that over the line.

I think its now becoming possible to aim fairly high (90/100 on mobile) with our Page Speed scores, but it does require getting most if not all of the Architecture Pillars above working together. Its worth learning each of these and understanding the pitfalls and limitations if you want really great page speed. Good luck and feel free to get in touch with any questions.

Footnote

The combined pillars can produce great results but you still need to load test before going live. Checkout the video below where I search for the breaking point using the loadtest tool. Please note that this node based load test tool should just be used for a guide. Before go live I recommend using a hosted load tool solution that has multiple geographic locations. Tests done based on one network location or device will result in a network bottle neck and give you false positives.

Bonus Video: https://www.youtube.com/watch?v=96YcxyhYh0U

Unicorn & Sitecore with custom rule configurations

Unicorn is one of the most widely used utilities for syncing Sitecore item changes between different environments. Sitecore 9 has introduced rule based configuration that is used to target configurations for different roles (ContentManagement, ContentDelivery etc..). We can also create custom rules by registering them in web.config.

This post will walk you through the use of custom rules to optimise Unicorn for development and deployment.

Environment rule configuration

Create a custom env rule by registering the below in web.config. This can then be used to target the configurations to be enabled/disabled based on the environment.

<appsettings> 
...
<!-- Possible values Development, Test, UAT, Production -->
<add key="env:define" value="Development" />    
... 
</appsettings>

Default Helix configuration uses serialization as the root folder within each module at the respective helix layer. You can also make different unicorn configurations to go to different folders by configuring the targetDatastore for that configuration.

<targetDataStore physicalRootPath="$(sourceFolder)\$(layer)\$(module)\serialization-once" />
Use this to target the configurations to write to serialization-once folder

<targetDataStore physicalRootPath="$(sourceFolder)\$(layer)\$(module)\serialization-dev" />
Use this to target the configurations to write to serialization-dev folder

The above configurations help differentiate the items that are serialized and synchronized only once and to be only synchronized on developer environments.

Sample Configuration for Developer Content Serialization

<configuration 
name="Project.Website.Serialization-dev"
description="Project Website Dev Unicorn items"
dependencies="Project.Website"
extends="Helix.Base"
env:require="Development">
<targetDataStore
physicalRootPath="$(sourceFolder)\$(layer)\$(module)\serialization-dev" />
<predicate
type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn"
singleInstance="true">
<include
name="Dev.Content"
database="master"
path="/sitecore/content/<site>/<devcontent>" />
</predicate>
</configuration>

Sample Configuration for New Items Only Serialization

This configuration becomes always update on developer environments.
<configuration 
name="Project.Website.Serialization-Once"
description="Project Website new items only"
dependencies="Foundation.*,Feature.*,Project.Core"
extends="Helix.Base">
<evaluator
type="Unicorn.Evaluators.NewItemOnlyEvaluator, Unicorn"
singleInstance="true"
env:require="!Development"/>
<!-- This will be New Items Only in All environments except Development -->
<targetDataStore
physicalRootPath="$(sourceFolder)\$(layer)\$(module)\serialization-once" />
<predicate
type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn"
singleInstance="true">
<include
name="Project.Content.Newitems"
database="master"
path="/sitecore/content/<site>/<new-items>" />
</predicate>
</configuration>

Unicorn rule configuration

A custom unicorn rule can be created by registering the below in web.config. This can then be used to apply configurations based on if unicorn is enable/disabled.

<appsettings> 
...
<!-- Possible values On, Off -->
<add key="unicorn:define" value="On" />
... 
</appsettings>

Having unicorn enabled in non development environments can impede the authoring quality of life especially when using Azure PaaS where the disk I/O is not that great. As part of the CI/CD once the unicorn sync has been performed we can disable unicorn using the following patch config. This config only works when unicorn rule is set to Off.

<configuration 
xmlns:patch="http://www.sitecore.net/xmlconfig/"
xmlns:role="http://www.sitecore.net/xmlconfig/role/"
xmlns:unicorn="http://www.sitecore.net/xmlconfig/unicorn/">
<sitecore
unicorn:require="Off"
role:require="ContentManagement Or Standalone">
<unicorn>
<configurations>
<patch:delete />
</configurations>
</unicorn>
</sitecore>
</configuration>

As part of the the deployment pipeline have a step to change the web.config unicorn:define value to Off so this above patch will take into effect.

Next Gen Image Compression in Sitecore

Spoiler: This post is not a post about Dianoga, I take a deep dive into Tiny PNG and Kraken.IO integrations into Sitecore. The results are worth checking out at the bottom.


At the start of the year, I’ve picked up where I left off, on page speed. Last year I took a deep dive into attempting to improve the page speed on Sitecore SXA sites by using some of Google’s recommended techniques to structure the page. If you haven’t already seen it, head on over the Sitecore Speedy and see some of the results we achieved.

I’ll be the first to admit that getting really good page speed scores isn’t easy. It takes a lot of different factors to come together. Just as a reminder, here is the main list that I would consider you need to check off to be winning at this game.

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

6) Javascript is not a page speed friend. Defer Defer Defer

For this post, i’m going to look at an alternative to Dianoga. I’m a big fan of Dianoga and have used it over the years to crunch loads of oversized images introduced by Content Editors. I will, however, say that it can add complexity to deployments and CI/CD pipelines and while some claim to have had success in Azure Apps, others have not.

On the flip side, content editors love Tiny PNG, which is one of the most popular image compression website utilities going around. Tiny PNG also has a developer API, so we have used this to build in a compression tool that can be used directly from your Sitecore toolbar.

The button below is hooked up to chat to Tiny PNG API. It will send across your image data and receive a compressed image back for storage.


Full disclosure, I’m not the first person to hook up Tiny PNG to the image library. I could find two other implementations

One will allow you to run a powershell script to connect to the Tiny PNG API and the other is a module to connect to the API on upload.


This implementation of the Tiny PNG API introduces the following variances:

  • A button in the CMS to crunch any single image.
  • A scheduled task that will process any image not already processed.
  • Error handling for when the API limits are reached
  • Logging that outlines which images were processed.
  • Before and After compression information stored in any Image field of choice.
  • A feature toggle to turn the whole feature on/off

All the source code is available at: https://github.com/Aceik/ImageCompression

Now let’s jump in have a look at the results just from crunching a few images down:

Without image compression:

Click to Enlarge Image

To compress the images on the page, we head on over to the “Compress” button in the Media tab that we have introduced.

Click to enlarge

A few examples of compression results taken from homepage images:

Before: 158.4 KB | After: 110.6 KB

Before: 197.8 KB | After: 135.3 KB

Before: 640.0 KB | After: 120.7 KB

After compressing all the images on the page the saving can be seen below.

Click to enlarge

So our total image size saving is 2.4MB – 1.3MB = 1.1MB

A pretty decent saving from just pressing the compress button on 27 homepage images. Also, consider that the user won’t notice any difference in image quality as this method uses lossless compression.


The compression achieved is great for helping us tick off one of the requirements for fast pages with Google. But as we are about to find out Google will likely still complain about two other criteria. When it comes to Google Page Speed insights a page that does not have properly processed images will bring up the following three recommendations:

Here is a break down of how we address each one:

  1. Serve image in next-gen formats – Image formats like JPEG 2000, JPEG XR, and WebP often provide better compression than PNG or JPEG, which means faster downloads and less data consumption. Learn more.
  2. Properly Size images – Your CSS layouts should be responsive and use modern image retrieval techniques that adapt the image size requested based on screen size. Read More
  3. Efficiently encode images – The Tiny PNG integration above will take care of this. This is all about compressing the image to as small as it can get without a visible loss of quality.

So assuming you have already achieved number three using the Tiny PNG integration or another source, let us look at how we can solve the next-gen image requirement.

As a quick side note the testing I did after converting the images to next-gen also ticked item number two above. I don't think this should be relied on however and its best to incorporate responsive images into your projects from the beginning.  

When looking into how to convert images to a next-gen format I opted to target webp. Google has a nice little page explaining the format here.

WebP is natively supported in Google Chrome, Firefox, Edge, the Opera browser, and by many other tools and software libraries.

Once again I opted to look for an API that would provide the conversion for me so that Sitecore could easily connect, send the image and then store the result. All without any extra hosting requirements. I opted to go with Kraken.IO image APIs as they have a free 100MB trial offer and well free is a good price when building proof of concepts. The integration is all available on Aceik’s github repository. Just signup for your own API keys add them to the module settings (in the CMS) and start converting.

To test out just how much this would impact the image payload size for the whole page, I once again converted all the images on the SXA habitat homepage.

Here are the results:

Click to enlarge

So our total image size saving is now 2.4MB – 0.79MB = 1.61MB

The reduction in size from a non-compressed image to a webp formatted image is truly impressive.

A few examples:


Conclusion

I can only conclude by saying that if page speed is really an important factor for your Sitecore project take a look at Tiny PNG. If you want to go next level with your image formats and achieve great compression try out the Kraken.IO API integration as it could be well worth the small subscription fee.


Results

CompressionTotal Image SizeSaving
None2.4 MB
Tiny PNG1.3 MB1.1MB
Kraken.IO (webp)0.79MB1.61MB

Notes:

The module and code mentioned in this blog post are available on Aceik’s Github account. This also contains installations instructions.

GitHub: https://github.com/Aceik/ImageCompression

After installation, your content editors will simply be able to compress and convert images as needed from within the CMS.

Click to enlarge

The Github Readme contains a run down and the standard settings inside Sitecore as shown below:

Accessing the JSS Dictionary in C#

This is a quick post to guide developers through gaining access to the JSS Dictionary in the backend C# code.

Why would you want to be able to do this?

The reason we originally had to do this was that our JSS Angular application had editable content from the dictionary that we also wanted to access in C#. In our particular case, it was to inject the content into an email template that would be sent to the user. To save duplicating content it made sense for both the front end and C# to have access to the same dictionary.

Where do we start?

The following assumes you have a Sitecore instance with JSS installed and a JSS application you are working on. Grab your favourite de-compilation tool (I use ILSpy) and locate the following DLL in the bin folder of your running Sitecore instance:

Sitecore.JavaScriptServices.Globalization.dll

Once you have that open in ILSpy you want to have a search for DictionaryServiceController

public class DictionaryServiceController : ApiController

The following method is what we want to use in our C# code:

public DictionaryServiceResult GetDictionary(string appName, string language)

It takes the unique application name (that belongs to your application) and the language (“en”) as a parameter. As a result, you will get back a dictionary object that you can use to lookup up your content.

This is the Controller that would normally be called via an API on the front end. So how do we call it from normal C# service for instance?

Firstly, the controller has a constructor that has three parameters that are injected via DI (Dependency Injection).

IConfigurationResolver configurationResolver, 
BaseLanguageManager languageManager, 
IApplicationDictionaryReader appDictionaryReader

Using ILSpy once again you can find that the above three parameters are all set up in the DI container via RegisterDependencies.cs in various JSS assemblies. The Controller itself is already registered in the DI Container as well, which is very handy.

If you have a look at showconfig.aspx in the admin tools you can see that a lot of the dependencies are registered via RegisterDependencies.cs

For example:

<configurator type="Sitecore.JavaScriptServices.AppServices.RegisterDependencies, Sitecore.JavaScriptServices.AppServices" patch:source="Sitecore.JavaScriptServices.AppServices.config"/>

Dependency injection is a whole other topic so I will leave that to your personal preference as to how you achieve it. For the purposes of the following complete code example, I have used the Services Attribute style setup. If you want to keep consistency with Sitecore you could also setup via the RegisterDependencies.cs class of your own and use a patch file to kick it off.


Example Service:

using Sitecore.Foundation.DependencyInjection; // Borrowed from habitat
using Sitecore.Diagnostics;
using Sitecore.JavaScriptServices.Globalization.Controllers;

namespace Sitecore.Foundation.JSS.Services
{
    public interface ITranslationService
    {
        string TranslateKey(string key);
    }

    [Service(typeof(ITranslationService), Lifetime = Lifetime.Transient)] 
    public class TranslationService : ITranslationService
    {
        private readonly DictionaryServiceController _controller;
        
        public TranslationService(DictionaryServiceController controller)
        {
            this._controller = controller;
        }

        public string TranslateKey(string key)
        {
            var dictionary = GetDictionary();
            if (dictionary.phrases.ContainsKey(key))
                return dictionary.phrases[key];
            Log.Error("Dictionary key {key} not found", this);
            return string.Empty;
        }

        private DictionaryServiceResult GetDictionary(string appName = "myAppName", string language = "en")
        {
           return _controller.GetDictionary(appName, "en");
        }
    }
}

Above is a simple service that can be used from just about anywhere in your C# code.

Simply change the appName and language as required to access the correct JSS dictionary. Also, remember to publish your app dictionary to the web database or you may get no results.


There we have it, accessing the JSS dictionary from C# in a nutshell. I hope this helps some other folks get this done quickly on JSS builds.

An Introduction to Sitecore Pipelines

What is a Sitecore Pipeline?

In Sitecore pipelines describe a series of discrete steps that are taken to achieve some objective.  If you think about writing code to handle an HTTP request for example you could create a monolithic class that does the job from end to end; however the pipeline approach is a number of classes that can be invoked in order.  First do this and then do that etc. 

There are many Pipelines in Sitecore.  You can view existing pipelines and the processors that they call using Sitecore Rocks in Visual Studio.  Right click on the site connection and choose Manage. Click on the Pipelines tab in the Visual Studio edit pane.  Click on one of the listed pipelines to see all the processors that are executed as part of the pipeline.  There are pipelines with a single processor at one end of the scale to the httpRequestBegin pipeline with 45 distinct steps at the other.

Why are they useful?

Thinking about the monolithic class above it would be very difficult to maintain or modify, It would also be truly massive.  So modularising it would make it much easier to maintain. 

It also makes it much easier to customise.  For example, if we consider a pipeline that has three processors it might be drawn something like

To add to the existing functionality we could include a new step like

Where we add some custom function after Step 1 and before Step 2. 

We could also replace an existing step completely

How are they defined?

Pipelines are defined using XML in sitecore.config.  In the example below we can see the httpRequestEnd pipeline definition.  The three processors are called in the order in which they are listed.  A parameters object is passed between them to provide continuity.  The final processor is also receiving four additional parameters from the config file.

<?xml version="1.0" encoding="utf-8"?>
<sitecore database="SqlServer" xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:security="http://www.sitecore.net/xmlconfig/security/">
…
<pipelines>   
… 
<httpRequestEnd>
      <processor type="Sitecore.Pipelines.PreprocessRequest.CheckIgnoreFlag, Sitecore.Kernel" />
      <processor type="Sitecore.Pipelines.HttpRequest.EndDiagnostics, Sitecore.Kernel" role:require="Standalone or ContentManagement" />
      <!--<processor type="Sitecore.Pipelines.HttpRequest.ResizePicture, Sitecore.Kernel"/>-->
      <processor type="Sitecore.Pipelines.HttpRequest.StopMeasurements, Sitecore.Kernel">
        <ShowThresholdWarnings>false</ShowThresholdWarnings>
        <TimingThreshold desc="Milliseconds">1000</TimingThreshold>
        <ItemThreshold desc="Item count">1000</ItemThreshold>
        <MemoryThreshold desc="KB">10000</MemoryThreshold>
      </processor>
    </httpRequestEnd>
…
    </pipelines>
…
  </sitecore>

How can I work with Sitecore Pipelines?

Existing Sitecore pipelines can be customised as outlined above and it is also possible to create a brand new pipeline from scratch

Customise existing Pipelines

First thing to do is to create a configuration patch to add the new processor class into the pipeline at the desired location.  As you can see from the code it is possible to pass variables to the processor.  Here we are adding a processor called NewsArticleLogEntryProcessor into the httpRequestBegin pipeline after the ItemResolver

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor type="Fourbyclub.CustomCode.CustomCode.Pipelines.httpRequestBegin.NewsArticleLogEntryProcessor,Fourbyclub.CustomCode" patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']">
          <NewsArticleTemplateID>{B871115E-609F-44BB-91A4-A37F5E881CA6}</NewsArticleTemplateID>
        </processor> 
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

Then we need to create the processor.  Inherit the HttpRequestProcessor and Implement the Process method.  All we are doing here is writing to the log if the requested item is a NewsArticle.

namespace Fourbyclub.CustomCode.CustomCode.Pipelines.httpRequestBegin
{
    using Sitecore.Pipelines.HttpRequest;
    using Sitecore.Diagnostics;

    // TODO: \App_Config\include\NewsArticleLogEntryProcessor.config created automatically when creating NewsArticleLogEntryProcessor class.

    public class NewsArticleLogEntryProcessor : HttpRequestProcessor
    {
        
        // Declare a property of type string:
        private string _newsArticleTemplateID;
        public string NewsArticleTemplateID { get { return _newsArticleTemplateID; } set { _newsArticleTemplateID = value; } }

        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if ((Sitecore.Context.Item != null) && (!string.IsNullOrEmpty(_newsArticleTemplateID)))
            {
                Assert.IsNotNull(Sitecore.Context.Item, "No item in parameters");
                // use util to get id from string property
                if (Sitecore.Context.Item.TemplateID == Sitecore.MainUtil.GetID(_newsArticleTemplateID))
                {
                    // view in log file later, so add FourbyclubCustomCode
                    Log.Info(string.Format("FourbyclubCustomCode: News Article requested is {0} and the item path is {1}", Sitecore.Context.Item.DisplayName, Sitecore.Context.Item.Paths.FullPath), this);
                }
            }
        }

    }
}

Create a new Pipleline

To create and new pipeline is a little more work but still very simple.  The first thing to do is to declare the pipeline with a configuration patch

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <logWriter>
        <processor type="Fourbyclub.CustomCode.CustomCode.Pipelines.logWriter.logWriterProcessor,Fourbyclub.CustomCode" />
      </logWriter>
    </pipelines>
  </sitecore>
</configuration>

The XML above will create a pipeline called logWriter that has a single processor called logWriterProcessor, which will be in the Fourbyclub.CustomCode.dll.

Pipelines must pass a PipelineArgs object to each processor as it is called so that needs to be defined

using Sitecore.Pipelines;

namespace Fourbyclub.CustomCode.CustomCode.Pipelines.logWriter
{
    public class LogWriterPipelineArgs : PipelineArgs
    {
        public string LogMessage { get; set; }
    }
}

At least one processor is needed to do the work of our pipeline

using Sitecore.Diagnostics;

namespace Fourbyclub.CustomCode.CustomCode.Pipelines.logWriter
{
    public class logWriterProcessor
    {
        public void Process(LogWriterPipelineArgs args)
        {
            Log.Info(string.Format("FourbyclubCustomCode: The message was {0}", args.LogMessage), this);
        }
    }
}

Finally we need to invoke the pipeline in our code somewhere.  Instantiate the LogWriterPipelineArgs and set the LogMessage.  Then call CorePipeline.Run and pass it the name of the pipeline and the args.object

var pipelineargs = new LogWriterPipelineArgs();
pipelineargs.LogMessage = "Requested item is not a News Article";
CorePipeline.Run("logWriter", pipelineargs);

Conclusion

Thank you for reading and I hope that this short introduction to Sitecore Pipelines has shown the power of pipelines to customise Sitecore and help to build maintainable code.  However we should always check if there is a way we can implement something using existing Sitecore functionality rather than going for a pipeline as a first resort. As with any customisation does each pipeline or processor added have a potential to increase the challenge of Sitecore upgrades?

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