Code Monkey home page Code Monkey logo

Comments (3)

devtombiz avatar devtombiz commented on August 17, 2024 2

OK, I have found another solution: creating and configuring a local puppeteer instance and passing all that to penthouse via critical:

async function findCriticalCss(htmlFile, browser, retryCount = 0) {
  return new Promise((resolve) => {
    gulp
      .src(htmlFile)
      .pipe(
        critical({
          base: "dist/",
          inline: true,
          target: {
            css: "critical.css",
            uncritical: "uncritical.css",
          },
          dimensions: [
            { height: 694, width: 500 },
            { width: 1600, height: 900 },
          ],
          concurrency: 1,
          penthouse: {
            browser: browser,
            timeout: 30000,
            unstableKeepBrowserAlive: true,
          },
        })
      )
      .on("error", async (err) => {
        console.log(`Error in ${htmlFile}: ${err}`);
        if (retryCount < 3) {
          console.log(`Retrying ${htmlFile}...`);
          await processFile(htmlFile, browser, retryCount + 1);
        }
        resolve(); // Always resolve to continue with the next file
      })
      .pipe(gulp.dest("dist"))
      .on("end", () => {
        console.log(`Processed ${htmlFile}`);
        resolve();
      });
  });
}

gulp.task("criticalCss", async function () {
  const htmlFiles = glob.sync("dist/**/index.html").sort();
  console.log("Finding critical CSS in all index.html files:");

  const browser = await puppeteer.launch({
    headless: "new",
    defaultViewport: null,
    args: [
      "--disable-dev-shm-usage",
      "--disable-setuid-sandbox",
      "--no-first-run",
      "--no-sandbox",
      "--no-zygote",
      "--single-process",
    ],
  });

  for (const htmlFile of htmlFiles) {
    await findCriticalCss(htmlFile, browser);
  }

  console.log("All files processed.");
});

Note: I think that the unstableKeepBrowserAlive option is critical for penthouse to work properly and go through all the files.

from critical.

devtombiz avatar devtombiz commented on August 17, 2024

OK, I found a workaround by using a shell script that start a new process each time and retry if it fails:

#!/bin/bash

find ./dist -name 'index.html' | while read -r file; do
  retry_count=0
  
  while [[ $retry_count -lt 3 ]]; do
    node inline-critical-css.mjs "$file"
    
    if [[ $? -eq 0 ]]; then
      echo "Successfully processed $file"
      break
    else
      echo "Failed to process $file. Retrying..."
      ((retry_count++))
      sleep 1
    fi
  done

  if [[ $retry_count -eq 3 ]]; then
    echo "Failed to process $file after 3 attempts."
  fi

  sleep 1
done
import path from "path";
import { generate } from "critical";

const processHTML = async (filePath) => {
  try {
    await generate({
      base: "dist/",
      src: path.basename(filePath),
      target: {
        css: "critical.css",
        uncritical: "uncritical.css",
      },
      dimensions: [
        { height: 694, width: 500 },
        { height: 1023, width: 500 },
        { width: 1600, height: 900 },
      ],
      inline: true,
      concurrency: 1,
    });
    console.log(`Processed ${filePath}`);
  } catch (err) {
    console.error(`Error processing ${filePath}: ${err}`);
    process.exit(1);
  }
};

const filePath = process.argv[2];
if (filePath) {
  processHTML(filePath).catch((err) => {
    console.error(err);
    process.exit(1);
  });
} else {
  console.log("No file path provided");
  process.exit(1);
}

It is slower, but I can go through all the files...

from critical.

bezoerb avatar bezoerb commented on August 17, 2024

🚀

from critical.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.