Skip to content

Commit

Permalink
use dropcss
Browse files Browse the repository at this point in the history
  • Loading branch information
tsubik committed Dec 9, 2024
1 parent 3dd6b6d commit 355f3b0
Show file tree
Hide file tree
Showing 4 changed files with 699 additions and 654 deletions.
19 changes: 11 additions & 8 deletions .env.default
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,30 @@ GFW_API_KEY=
MAPBOX_API_KEY=
DOCUMENTS_MINDATE=

// Transifex token
# Transifex token
TX_TOKEN=

// Sentry DSN
# Sentry DSN
SENTRY_DSN=
SENTRY_ORG=
SENTRY_PROJECT=
SENTRY_AUTH_TOKEN=
// for development env to disable pushing release to sentry
# for development env to disable pushing release to sentry
SENTRY_DISABLE_RELEASE=

// Osano Cookie Consent Manager
# Osano Cookie Consent Manager
OSANO_ID=

// Hotjar - you can disable for e2e or development in prod mode
# Hotjar - you can disable for e2e or development in prod mode
# DISABLE_HOTJAR=true

// Features
# Critical CSS
CRITICAL_CSS=true

# Features
FEATURE_COUNTRY_PAGES=false
// map page should be enabled only in dev environment
# map page should be enabled only in dev environment
FEATURE_MAP_PAGE=true

// Next
# Next
NEXT_TELEMETRY_DISABLED=1
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dayjs": "^1.11.11",
"deck.gl": "7.3.6",
"dotenv": "^16.4.5",
"dropcss": "^1.0.16",
"foundation-sites": "^6.8.1",
"fuse.js": "^7.0.0",
"html-react-parser": "^5.1.10",
Expand Down
76 changes: 72 additions & 4 deletions pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,56 @@
import React from 'react';
import { Html, Head, Main, NextScript } from 'next/document';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
import path from 'path';
import fs from 'fs';
import dropcss from 'dropcss';

import GoogleTagManager from 'components/layout/google-tag-manager';

export default function Document({ locale }) {
const isCriticalCssEnabled = process.env.NODE_ENV === 'production' && process.env.CRITICAL_CSS === 'true';

class CustomHead extends Head {
constructor(...args) {
super(...args);
if (isCriticalCssEnabled) {
this.context.optimizeCss = true;
}
}

getCssLinks(files) {
const links = super.getCssLinks(files);
if (links && links.length && isCriticalCssEnabled) {
links.forEach((link) => {
link.props.media = 'print';
});
links.push(
<script dangerouslySetInnerHTML={{ __html:`
document.querySelectorAll('link[media="print"]').forEach(link => {
link.onload = function() { this.media = 'all'; }
});
`}} />
)
}

return links;
}
}

export default function CustomDocument({ locale, criticalCss }) {
const withOsano = !!process.env.OSANO_ID;
const withGTM = !!process.env.GOOGLE_TAG_MANAGER_KEY;
const withHotjar = process.env.DISABLE_HOTJAR !== 'true' && process.env.ENV === 'production';
const language = locale || 'en';

return (
<Html lang={language}>
<Head>
<CustomHead>
{withOsano && <link rel="preconnect" href="https://cmp.osano.com" />}
{withGTM && <link rel="preconnect" href="https://www.googletagmanager.com" />}
{withHotjar && <link rel="preconnect" href="https://static.hotjar.com" />}
</Head>

{criticalCss && <style dangerouslySetInnerHTML={{ __html: criticalCss }} />}
</CustomHead>
<body>
{withOsano && <Script src={`https://cmp.osano.com/${process.env.OSANO_ID}/osano.js`} strategy="beforeInteractive" />}
<Script src={`/${language === 'en' ? '' : language + '/'}translations.js`} strategy="beforeInteractive" />
Expand All @@ -27,3 +61,37 @@ export default function Document({ locale }) {
</Html>
);
}

CustomDocument.getInitialProps = async (ctx) => {
const initialProps = await Document.getInitialProps(ctx);

let criticalCss = null;

if (isCriticalCssEnabled) {
const cssDirPath = path.resolve(process.cwd(), '.next/static/css'); // Path to the CSS directory
const cssFiles = fs.readdirSync(cssDirPath).filter(file => file.endsWith('.css'));

if (cssFiles.length > 0) {
// Get the first CSS file
const cssFilePath = path.join(cssDirPath, cssFiles[0]);
const css = fs.readFileSync(cssFilePath, 'utf8');

const html = `
<html>
<body>
${initialProps.html}
</body>
</html>
`;
const label = `generating critical CSS for ${ctx.pathname}`;
console.time(label);
criticalCss = dropcss({
css,
html
}).css;
console.timeEnd(label);
}
}

return { ...initialProps, criticalCss };
};
Loading

0 comments on commit 355f3b0

Please sign in to comment.