0
0
Wordpressframework~30 mins

Critical rendering path optimization in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
Critical Rendering Path Optimization in WordPress
📖 Scenario: You manage a WordPress website that loads slowly because it loads all CSS and JavaScript files immediately. You want to improve the page load speed by optimizing the critical rendering path.This means you will load only the essential CSS inline and defer non-critical CSS and JavaScript files to load later.
🎯 Goal: Build a WordPress theme setup that inlines critical CSS in the header and defers loading of non-critical CSS and JavaScript files to improve page load speed.
📋 What You'll Learn
Create a variable holding the critical CSS styles as a string
Create a variable holding the URL of a non-critical CSS file
Add the critical CSS inline in the <head> section
Enqueue the non-critical CSS file with the media="print" attribute and load it asynchronously
Enqueue a JavaScript file with the defer attribute
💡 Why This Matters
🌍 Real World
Websites often load many CSS and JavaScript files that block rendering. Optimizing the critical rendering path helps pages load faster and improves user experience.
💼 Career
Front-end developers and WordPress theme developers use these techniques to improve website performance and SEO rankings.
Progress0 / 4 steps
1
Setup Critical CSS Variable
Create a PHP variable called $critical_css that contains this exact CSS string: body { background-color: #fff; color: #333; }
Wordpress
Need a hint?

Use single quotes around the CSS string and assign it to $critical_css.

2
Add Non-Critical CSS URL Variable
Create a PHP variable called $non_critical_css_url and set it to the string get_template_directory_uri() . '/css/non-critical.css'
Wordpress
Need a hint?

Use get_template_directory_uri() to get the theme URL and append the CSS path.

3
Inline Critical CSS and Enqueue Non-Critical CSS
Add a function called enqueue_critical_and_non_critical_css hooked to wp_head that:
1. Echoes the <style> tag with the $critical_css content inline.
2. Enqueues the non-critical CSS file using wp_enqueue_style with handle 'non-critical-css', URL $non_critical_css_url, no dependencies, no version, and media="print".
3. Adds an onload attribute to the non-critical CSS link to set this.media='all' for asynchronous loading.
Wordpress
Need a hint?

Use wp_head hook to output inline CSS and enqueue the non-critical CSS with media print and onload attribute.

4
Defer JavaScript Loading
Add a function called defer_parsing_of_js hooked to script_loader_tag that adds the defer attribute to the script tag with handle 'theme-script'. Then enqueue a JavaScript file with handle 'theme-script', URL get_template_directory_uri() . '/js/theme.js', no dependencies, no version, and in footer.
Wordpress
Need a hint?

Use script_loader_tag filter to add defer attribute and enqueue the script in the footer.