Feb 09 2020
Feb 09

With performance being a continuous bottleneck for enterprises trying to deliver an exceptional digital experience to customers and please search engines, this blog will serve as a sight to the sore eyes. 

Earlier, we covered tips and tricks for beginners to help them optimize the site performance.  Today, we are taking this forward to illustrate some intermediate-level techniques for optimal results. The many ways to configure web performance for your Drupal website are listed below-

 

1.  Theme optimization

Theme optimization is an essential technique to enhance performance. Because, when developers create new themes, they override the required templates such as home page layout or node page, and for the rest of the pages, they override CSS; leading to the addition of a lot of unwanted layers in the HTML.

Follow the steps mentioned below to optimize the theme for your Drupal website-

  1. Remove blank spaces and comments manually from .tpl
  2. Ensure there is no indentation in .tpl
  3. Turn on CSS & JS aggregation in the performance page
  4. Remove duplicate files and combine similar ones to reduce the CSS file size
  5. Move codes to functions in a custom common module. Use functions for similar problems instead of coding separately.

 

2.  Drupal external caching:


Desktop, ipad, and phone showcased with other iconsSource- Cloudways

 

There are a few methods in Drupal that can manage the CMS interaction with an external cache. This can be done using contributed modules, like-

A.   Advanced CSS/ JSS Aggregation

Known as AdvAgg, it ensures the improvement in the frontend performance of your site. You can also compare before and after results using Google’s PageSpeed Insights tool.

B.    Memcache

With Memcache, you can directly discharge cache bins into RAM; thereby speeding up the cache and making room for MySQL to breathe.

C.     Redis

Redis is an open-source (BSD licensed) & in-memory data structure store that can be used as a smart cache with the proper eviction policy. When implemented in a similar fashion, it can prove to be the most effective way by which the application can access stored content within it and improve the cache hit ratio substantially.

Know more about the clear cache tag module and how it helps in optimizing the website performance.


3.  Devel module:  

Devel is an amalgamation of modules, encompassing helper functions, admin pages, and additional development support. One can use Drush commands to use it during the development process to evaluate the query execution time or the number of times function was executed on a particular page.

4.  Sprite image: 

Sprites are 2-D images that are constituted into one from small images, defined at X and Y coordinates. To display a single image from the combined image, you could use the CSS background-position property, thereby showcasing the exact position of the image to be displayed.

5.  Lazy-load images

Lazy loading is a shrewd technique that involves displaying content only when it’s visible to users as they scroll down the screen. This comes handy for those sites which comprise a lot of images and don’t intend to waste the bandwidth by loading the whole page every time the user comes on it. 

Thus, images are visible only when the user scrolls.

6.  Implementing AMP standard to provide lightning-fast page loading on mobile devices

AMP refers to Accelerated Mobile Pages. It ensures the optimization of web pages for faster loading on mobile devices by providing content through lightweight pages. This certainly aligns with Google’s motive of making the web a more accessible and enjoyable place for users of mobile devices.

AMP is the open-source framework that lets you build pages which are stripped-down/lightweight version of your main pages by eliminating speed-taxing elements impacting load time.

So, whenever a standard webpage’s AMP alternative is available, a link to the AMP version is placed on the page via an HTML tag and then it is what displayed to the mobile device user.

This way, the implementation of AMP can boost the loading speed of your web pages, and hence, improve the end-user experience. 

7.  Accelerating your 404 responses with the Fast 404 module

Drupal logo, a meter, and other tools to measure performanceSource: Web peppers

The average site with an average module load consumes around 60-100MB of memory on the server to deliver a 404. However, Drupal Fast 404 module comprises a common method that handles both missing image & file 404 errors to fix the issues using less than 1MB of memory; depending on the method you choose - aggressive or super-aggressive.

8.  S3 File System

S3 File System or s3fs provides an additional file system to your Drupal site, which is stored in either Amazon’s Simple Storage Service (S3) or any other S3- compatible storage service. It’s up to you whether you want to use S3 File System as the default one, or only for individual fields. This is beneficial for the sites that have distributed their load across multiple servers, as the mechanism used by Drupal’s default file systems is not sustainable under such a configuration.

9.  Content delivery network 

Content Delivery Network module facilitates easy integration for Drupal sites. It modifies file URLs so that files (for example, CSS, JS, images, fonts, videos, etc.) are downloaded from a CDN instead of your web server.

However, only origin pull CDNs are supported. You just need to replace the existing URL with another domain name- thereby, allowing CDN to automatically pull the files from your server (the origin).

10.  Pick Nginx over Apache 

Apache and Nginx are the two common open-source web servers, however, the latter is quite faster and consumes considerably less space than the former one. 

Nginx has been designed to resolve the C10K problem - the most common problem that web servers (like Apache) face in supporting a large number of simultaneous connections, i.e, more than 10k connections at once.

Thus, Nginx comes as a quick fix for performance issues. You can opt for it without the need of changing your actual application code. It will seamlessly integrate with your Drupal code.

11.  Leverage browser’s cache for images and files

Leveraging your browser’s cache implies that you can specify for how long web browsers should retain images, CSS and JS stored locally. That way, the user’s browser will download less data while browsing on your site, thereby improving site performance. Below are the examples of the same for different web servers-

  • For Nginx web server :
 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {

expires 365d;

}

location ~* \.(pdf)$ {

expires 30d;

}

  • For Apache web server :


It should be added to your .htaccess file.

 ## EXPIRES CACHING ##

<IfModule mod_expires.c>

ExpiresActive On

ExpiresByType image/jpg "access 1 year"

ExpiresByType image/jpeg "access 1 year"

ExpiresByType image/gif "access 1 year"

ExpiresByType image/png "access 1 year"

ExpiresByType text/css "access 1 month"

ExpiresByType text/html "access 1 month"

ExpiresByType application/pdf "access 1 month"

ExpiresByType text/x-javascript "access 1 month"

ExpiresByType application/x-shockwave-flash "access 1 month"

ExpiresByType image/x-icon "access 1 year"

ExpiresDefault "access 1 month"

</IfModule>

## EXPIRES CACHING ##

  • Cache-control
 # 1 Month for most static assets

<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">

Header set Cache-Control "max-age=2592000, public"

</filesMatch>

  • gzip compression
 mod_gzip_on Yes

mod_gzip_dechunk Yes

mod_gzip_item_include file .(html?|txt|css|js|php|pl)$

mod_gzip_item_include handler ^cgi-script$

mod_gzip_item_include mime ^text/.*

mod_gzip_item_include mime ^application/x-javascript.*

mod_gzip_item_exclude mime ^image/.*

mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

12.  Drupal coding standards should meet

Coding standards specify the set of rules for programmers to ensure best practices like consistent formatting, indentation, and many more rules.

Drupal’s coding standards are articulated in English so that anyone working with Drupal team around the globe, which is common today, standards can eliminate any communication differences.

Further, many programmers come to Drupal from multiple programming language backgrounds, each with their syntax and style. Therefore, having a precise set of standards to look upon help in keeping the codebase consistent.

These standards, further, specify the guidelines on how to style and format your code precisely, especially concerned with its appearance and readability ease. This includes things like indentation, whitespace, and line length. 

Ensuring that all code abides by the given guidelines, Drupal acknowledges consistency & integrity in all its projects, making it easier for documentation. The API module itself parses the information to produce a document, which can be seen here. The documentation is generated by the specific format of the comments and a variety of tags in the source code to get detailed information on the code.

13.  Ensuring code security is a MUST

Security is the foremost issue for any developer that he or she must take care of, undividedly; no matter whether you are writing a PHP snippet or an entire module. 

The given basic rules will help you avoid any security breach if followed properly-

  • Apply check functions on the output obtained to prevent cross-site scripting attacks.
  • User-submitted content shouldn’t be placed directly as-is into HTML ever.
  • Take benefit of the database abstraction layer to avoid SQL injection attacks
  • Use db_rewrite_sql() to respect node access restrictions.

14.  DB query optimization in codes

Performance tuning can be a challenging task, especially when you tend to work with large-scale data. Even the smallest change can have a significant (positive or negative) impact on performance.

Query optimization can be stated as whenever a developer or the database engine revamps a query in such a way that SQL Server is capable of returning the same results more efficiently.

For more ease, you can follow these steps-

1.  Join DB queries whenever possible

2.  For any DB updates and insertion, use core API

3.   Follow Drupal coding standards

15.  DB table optimization

DB table optimization in Drupal refers to the refinement of all the administrator-selected tables in the database and displaying its sizes. Enable notifications stating the necessity to analyze tables, maintenance, and carry out repair operations. 

With it, you can prevent crashing of tables during regular cron.php executions.

16.  Table indexing 

A database index is a data structure that ensures the boost in the speed of operations in a table. You can create indexes using one or more columns for rapid & random lookups, and efficient ordering of access to records.

17.  Use Defer attribute for external js file to load the page faster

The role of the Defer attribute is to indicate to the browser that it should load the script in the background, while continuously working on the page. Once the script gets loaded, you can run it. 

The advantage here is that scripts with the Defer attribute never let the browser block the page. 

E.g. js/admin_toolbar.js: { attributes: { defer: true } }

18.  Upload compressed image for better performance results

Using compressed or smaller- sized images will help in saving bandwidth, which is appreciated by Networks and browsers as well.

Also, before starting the modification of images, ensure that you have chosen the best file type. There are several types of file that you can use:

  1. PNG - creates higher quality images, but the downside is its large file size. Though it was created as a lossless image format, it can also be lossy.
  2. JPEG - uses lossy and lossless optimization. You can adjust the quality level for a good balance of quality and file size.
  3. GIF - utilizes 256 colors only, making it suitable for animated images. It only uses lossless compression. 

Wrapping Up

With all the given methods from implementing a CDN to clearing caching, lazy-loading images, fixing 404s, and aggregating CSS/JS files, you can fix your Drupal-powered website’s performance extensively.

Jan 25 2020
Jan 25

A sluggish-performing Drupal website not only impacts user experience but also worsens the ranking of the site on search engines like Google who are fanatical about faster page load times (user experience mostly).

Contrary to it, when a Drupal-powered website is perfectly optimized for performance, it can tackle many million visits on the site each day. 

There are multiple ways to configure web performance for optimal results. This blog post will walk you through the checklist of feasible performance optimization techniques for your Drupal website at a beginner level.

Beginners’ Level Tricks to Load Drupal Site Faster

There are several methods at the beginner level that can be implemented to speed up page loading. Specific Drupal tools and modules are listed for the same-

  1. Core Caching: Go to Extend -> Module

These two Drupal modules, “Internal Dynamic Page Cache” and “Internal Page Cache”, should be installed and enabled by default. 

  • Internal Page Cache:

Internal Page Cache is beneficial for sites that have several millions of unregistered users

This module is beneficial for sites that have several millions of unregistered users. It stores the entire page in the cache so that whenever a new user or even the same user revisits that page, it can load faster than ever without the need of putting information together from scratch.

  • Internal Dynamic Page Cache: 

This module is designed to cache small sections of each page for all users, no matter if the users are logged in or not. The objective is to accelerate the building of the website page on the go.

2. Twig Caching: 

Twig caching is deployed as a template engine for theming purposes in Drupal 8. It relies on its own cache of compiled Twig templates, which is separate from other caches.

Go to sites/default/ & copy your default.services.yml file to services.yml and check below config settings:

  • twig.config : debug: false
  • auto_reload: null
  • cache: true

These commands will help one on/off caching for the twig template.

3. Page Caching:

The information available online is valid for a certain period of time. In such a scenario, it is better to define a corresponding maximum age. However, in Drupal 8, there doesn’t exist any feature that validates data for a limited time. Rather, it caches data permanently and relies entirely on cache tags for invalidation.

Therefore, this module depicts the maximum time duration for a cached page. Whatever age we set here in Cache max-age, implies the maximum age that our site tells browsers to keep cached information/ data. 

  • To enable caching, navigate through Configuration- Development-Performance. 
  • Activate “Cache pages for anonymous users” by selecting the minimum time for the cache lifespan as well as the termination of the cached pages.

Drupal logo and Speed word written                             Source: CloudReviews

4. Bandwidth Optimization: Go to configuration -> development -> performance

Bandwidth optimization is performed to reduce both the size and the number of requests made to your website

Drupal 8 has already eliminated “compress cached pages”. Instead, it has introduced a default setting where one can optimize external resources efficaciously. This bandwidth optimization is performed to reduce both the size and the number of requests made to your website. 

With Drupal 8, you can simply aggregate CSS & JavaScript files to load them together faster with just a handful of aggregates.

5. Views Caching :

The Views caching module helps in displaying content in various ways. Views instances should be cached as the best practice so that when accessed, a cached copy is returned instead of having to rebuild each view every time it’s loaded.

There are 4 options in views caching :

  1. Tag-based

Cache tags make Drupal aware of the entities used during a page view. This implies that Drupal saves the cache tags along with the data it caches. Thus, if it needs to clear the caches because one entity is updated (let’s assume node with ID 55), instead of erasing all caches, it can easily find out which caches actually used node 55 and clear only those.

2. Time-based

The cached data remains valid for a certain period of time. To set time-dependent caches, one can use cache max-age and set the time duration for a cached page, further exceeding which, it will be erased or expired.

3. None (no caching)

It implies that there is no caching associated with the view.

4. Views custom cache tag

Views automatically add cache tags to every view in order to nullify content whenever it is updated (and can be cached maximum possible until they do).

However, Drupal 8 encompasses a single list cache tag for every entity type. Every view that enumerates nodes is tagged with node_list and will be invalidated when a node is added, changed, or deleted.

Views contain filters. They list nodes of a specific type or those which are tagged with certain terms and a combination of three other filters. With the usage of more specific cache tags, it is possible to update views that actually might list the changed node. 

This module allows developers to set different cache tags based on the configuration of the view. It is also possible to set cache tags based on arguments/contextual filters.

6. Clear Cache Tag

The caching process in Drupal is carried out through tags. The Clear Cache Tag module also uses the tags in the form of strings to pass it in sets and clear the required cache items only, unlike the conventional practice, which involves the cache clearance of the whole site.

This module helps website developers save a considerable amount of time and effort, which otherwise would have been dedicated to maintaining information. Besides, frequent caching can aggravate the website loading time, thereby impacting user-experience extensively.

7. Image Optimization


Image optimization module configuration                       Source: Drupal.org

 The ultimate goal is to reduce the file size as much as possible without sacrificing quality

The image size that you choose for your website has a profound impact on your website’s speed and performance. The right approach to ensure image optimization is to adopt correct sizing and formatting (JPEG, GIF, or PNG). The ultimate goal is to reduce the file size as much as possible without sacrificing quality. Fortunately, Drupal 8 core offers tools to control and optimize image sizes. Use the Image style features to have different image sizes for different devices like tablets and mobiles.

You can change the compression ratio of an image. By default in Drupal 8, it is set to 75%.

1. To change the ratio, go to Configuration -> media -> Image toolkit

2. change the % and Save configuration

8. Use Syslog For The Error Log

Syslog delivers valuable information for use in the system management and security auditing

The Syslog module records events by sending messages to the logging facility of your web server’s operating system. Syslog is an operating system administrative logging tool that delivers valuable information for use in the system management and security auditing. Suited for medium and large sites, Syslog offers filtering tools to route messages as per their type and severity. 

It can significantly improve the performance of the site.

Watch out how to set up the Syslog module-

[embedded content]

9. Disable Unused Modules

List out all the modules that you don’t need and disable them as these only add to the total overhead for additional PHP code to execute on each page load and demand extra CSS and JavaScript files, even if you are not using the module for anything.

In case you have modules that you use seldom, it’s suggested to disable them and try to find an alternate method to achieve the same result. 

10. Regularly Update Core, Contributed Module, and Themes Of Your Drupal Site

It is best to be cognizant of what each update offers and test things out before pushing them live

Per the proven methodologies and practices, you should keep an eye on updates to the Drupal core and contributed modules. The updates are released frequently and encompass performance improvements, so keeping them maintained is essential. 

Simultaneously, it is best to be cognizant of what each update offers and test things out before pushing them live.

Final Words

There are several factors to take into account which can hamper the performance of your Drupal site. Therefore, you must make sure that your site is cached appropriately, images are of the desired size, and unused modules are discarded. These factors consolidated with adequate bandwidth usage will give your Drupal site an edge against the competitors.

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web