Add CSS file to the HTML head by substituting the <link> tag

Searching for a possible npm-based solution to replace:

<link rel='stylesheet' href='style.css'>

with

<style><!-- actual contents of the style.css file here --></style>

to simplify the process of building a lightweight static website. Many packages found that inline CSS into every DOM element, which is not the desired outcome.

The current build pipeline includes:

  1. Compiling SASS (minified)
  2. Minifying HTML
  3. Injecting minified CSS in HTML <style> tag.

Focused on finding a solution for step three.

Attempted using npm packages such as:

  • inlineCss: incorrectly applies styles to each element.
  • Styliner: appeared to be broken.

Answer №1

When faced with a similar need, I found a solution that worked for me. My method involves leveraging Gulp to achieve the following tasks:

  1. Transform Sass files into CSS
  2. Automatically add link tags to my HTML file without manual intervention
  3. Utilize these link tags to extract the source href of the CSS file, then insert the contents of this CSS file into the HTML by replacing the original link tag.

To see the entire Gulp setup, you can check out the complete gulp file here. By running the command gulp build, all the mentioned steps are executed seamlessly (at line #42 in the linked file).

Answer №2

As of now, I have found a workaround for the issue by creating a basic script that handles this replacement task effectively:

inline-css.js:

const fs = require('fs');

const htmlContent = fs.readFileSync('dist/index.html', 'utf8');
const cssContent = fs.readFileSync('dist/style.css', 'utf8');

const inlinedHtml = htmlContent.replace(
    '<link rel="stylesheet"href="style.css"type="text/css"charset="utf-8">',
    "<style>" + cssContent + "</style>");

fs.writeFileSync('dist/index.inlined.html', inlinedHtml);

To execute it, simply use $ node inline-css.js.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on extracting data from a JavaScript table using Python

Looking to extract information from a table on this page: . There are a total of 18 pages, but the url remains constant for each page. My usual method involves using BeautifulSoup to scrape data from HTML pages. However, in this case, the required data is ...

Exploring the concept of Variable Scope within a jQuery promise

Picture yourself executing the following code snippet within a JavaScript function named Fetch. function Fetch(context) { var request = $.ajax({...}); request.done(function(response) { // It appears that context is accessible here and in scope. ...

What steps can be taken to safeguard the title of the document in the top window from being altered by any iframe or script?

My typical approach is to delete and redefine the title property like in the code snippet below: if (delete document.title) { Object.defineProperty(document, 'title', { get: getter, set: setter, enumerable: true, ...

What is the most efficient method for executing multiple variable=function() and determining when all tasks have been finished?

I am facing the issue of having multiple variables that need to be calculated before being saved as a JSON file. These calculations are done using a function, but when run asynchronously, they end up undefined. After reading about promises, it seems like t ...

Using .load() function in jQuery prevents .mouseenter() from functioning properly on loaded content

I'm facing an issue with a page that has a navigation bar loading content from another page into a content div when a navigation item is clicked. The loaded content includes various divs, one of which has the style display: none. This hidden div sits ...

Place the icon directly below the text

Can anyone please advise on the necessary input to position the icon BELOW/UNDER the text? <a href="#"><div class="resume"> <h4><i class="fa fa-address-card" style='display: block' ></i> Resume</h4> </ ...

Perform an API request to retrieve text content

I am currently utilizing Spark AR to develop a straightforward effect that retrieves text from an API and showcases it. Below is the code I am working with: const Scene = require('Scene'); const Diagnostics = require('Diagnostics'); c ...

What is the best way to eliminate tags from a BeautifulSoup-scraped list?

When using beautifulsoup to scrape a page, I am trying to extract the "title" by searching for specific tags: title = [text.find_all('h1', {'class', 'entry-title'}) for text in texts] The resulting output is a list like this: ...

Passing predefined functions to asynchronous functions can be achieved by simply defining the

I am facing a challenge in passing a predefined function within an async function. The piece of code below is functioning flawlessly: async.auto({ getAccessToken: function (callback) { let x = { access_token: signToken({ userId: u ...

Vue.js 2: Keep an eye on changes, but wait until after the initial data fetch

I recently entered the Vueverse (using Vue.js 2) and I'm encountering some challenges with the watch feature. When the component is mounted, I fetch data from an API and use it to set the value of a radio button. Essentially, I have two radio buttons ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

Is it possible for me to create a variable that is assigned the width of the page as its value?

As I work on building a website for my company, I encountered an issue where certain divs overlap when the page is resized smaller. I am looking for a solution to dynamically adjust the CSS using JavaScript based on the width of the page. Despite attempti ...

How can I ensure text remains confined within the parent div when working with Bootstrap?

I'm having trouble keeping the text and links within their parent div. Even though I set the outer boundary as col-sm-8, the text and links are overflowing. I'm not sure what I'm doing wrong, but the code I am using is shown below. I have a ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

The reset function for the selector is failing to properly reset the data within the table

I need help with a selector that has multiple options and a reset button. When the reset button is clicked, it should reset the selector back to the first option. Although the selector resets as expected when the button is clicked, the data in the table r ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

Utilizing the power of Bootstrap, you can create a row of eye-catching

I am struggling to get 3 columns of cards to display in a row using bootstrap and CSS. Currently, only 2 columns are showing up. Here is the code snippet: <style type="text/css"> .card{ width: 350px; } </style> ...

"Using HTML to assign a unique identifier to an image within

Apologies in advance for any errors as I am relatively new to html. I am attempting to construct a table with images that have onclick events, so that each clicked seat is tracked and its id is added to a list to change the class. Each image has been give ...

Unable to refresh Django table data with Ajax

Currently embarking on my first web application project using Django. The table interface in the code snippet below successfully renders data initially, but I am encountering issues with the Ajax call that is supposed to trigger the get_more_tables functio ...

Incorporate the latest value into an array of objects using JavaScript, taking into account its frequency

Hey there, I have an array of objects where I need to add a new property or value to each object based on its order number occurrence. For example, in the array of objects, there is a property called order number. If an object contains the highest order n ...