Skip to main content

Unnecessary CSS on Initial Load

Another issue that we may encounter is the loading of unnecessary CSS on the initial page load. This can be caused by poor use of media queries or inefficient CSS usage.

Ector exposes a hook called asyncCss that allows loading CSS asynchronously, avoiding blocking the page load. Use this hook to register the CSS files required by the module, loading them in a non-blocking asynchronous manner.

Using the asyncCss Hook

To load CSS asynchronously, you need to register your CSS files using the asyncCss hook in the module. Here’s how to do it:

Steps to Implement Asynchronous CSS Loading

  1. Define the Hook in the Module:

    • Open the module file and locate the function that registers the CSS.
  2. Register CSS with the asyncCss Hook:

    • Modify the function to use the asyncCss hook to register the CSS files for asynchronous loading.
public function hookAsyncCss($params)
{
// Add the CSS files to be loaded asynchronously
$this->context->controller->registerStylesheet(
'module-modulename-style',
'modules/modulename/views/css/style.css',
[
'media' => 'all',
'priority' => 100,
'inline' => false,
'async' => true
]
);
}
  1. Verify Asynchronous Loading:
    • After implementing the asynchronous registration of CSS, verify that the CSS files are loaded correctly without blocking the page load.

Benefits of Asynchronous CSS Loading

  • Improved Loading Speed:
    • By loading CSS asynchronously, the page can be displayed more quickly, enhancing the user experience.
  • Reduced Render Blocking:
    • Asynchronous loading of CSS reduces render-blocking time, allowing the main content of the page to be displayed without delay.

Conclusion

Using Ector's asyncCss hook to load CSS asynchronously is an effective way to improve site performance, reduce initial load time, and enhance the user experience. Make sure to register the necessary CSS files for the module asynchronously to avoid blocking during page rendering.