How do I optimize JavaScript and CSS in Magento?

Optimize JavaScript and CSS in Magento

Step 1: Merge JavaScript and CSS Files

Merging JavaScript Files:

  1. Go to the Admin Panel:
    • Navigate to Stores > Configuration > Advanced > Developer.
  2. Configure JavaScript Settings:
    • Under the JavaScript Settings section, set "Merge JavaScript Files" to "Yes".

Merging CSS Files:

  1. Go to the Admin Panel:
    • Navigate to Stores > Configuration > Advanced > Developer.
  2. Configure CSS Settings:
    • Under the CSS Settings section, set "Merge CSS Files" to "Yes".

Step 2: Enable JavaScript and CSS Minification

Minifying JavaScript Files:

  1. Go to the Admin Panel:
    • Navigate to Stores > Configuration > Advanced > Developer.
  2. Configure JavaScript Settings:
    • Under the JavaScript Settings section, set "Minify JavaScript Files" to "Yes".

Minifying CSS Files:

  1. Go to the Admin Panel:
    • Navigate to Stores > Configuration > Advanced > Developer.
  2. Configure CSS Settings:
    • Under the CSS Settings section, set "Minify CSS Files" to "Yes".

Step 3: Enable JavaScript Bundling

  1. Go to the Admin Panel:
    • Navigate to Stores > Configuration > Advanced > Developer.
  2. Configure JavaScript Settings:
    • Under the JavaScript Settings section, set "Enable JavaScript Bundling" to "Yes".

Step 4: Use Content Delivery Network (CDN)

Configure CDN:

  1. Choose a CDN Provider:
    • Providers like Cloudflare, Akamai, or Amazon CloudFront offer CDN services.
  2. Set up CDN in Magento:
    • Navigate to Stores > Configuration > Web.
    • Under Base URLs and Base URLs (Secure), update the Base URL for Static View Files and Base URL for User Media Files to point to your CDN URL.

Step 5: Asynchronous and Deferred Loading

Asynchronous and Deferred Loading:

  1. Edit JavaScript Includes:
    • Add async or defer attributes to your JavaScript <script> tags.
    <script src="path/to/script.js" async></script>
    <script src="path/to/script.js" defer></script>
            
  2. Use Extensions:
    • Install extensions that handle asynchronous and deferred loading for you, such as "Amasty Speed Optimization."

Step 6: Optimize Inline CSS and JavaScript

Inline Small CSS and JavaScript:

  1. Identify Small Files:
    • Determine which CSS and JavaScript files are small enough to inline (typically less than 1-2 KB).
  2. Edit HTML Templates:
    • Add the small CSS and JavaScript directly into the HTML templates where they are needed.
    <style>
    /* Inline small CSS */
    body {
        background-color: #fff;
    }
    </style>
    
    <script>
    // Inline small JavaScript
    console.log('Hello, world!');
    </script>