Create an immediate impact by injecting CSS

I currently have the following code set up:

style.js:

function applyStyle(str) {
    var element = document.createElement('style');
    element.innerHTML = str;
    document.body.appendChild(element);
}
var style = 'body {'
    style += '    color: red;'
    style += '}'
applyStyle(style);

and configuration.json:

{
  "name": "example",
  "description": "example description",
  "manifest_version": 2,
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["http://example.com"],
      "js": ["style.js"]
    }
  ]
}

The current setup is functional, however, it applies the styles only after the webpage has finished loading. How can I achieve an instant effect, similar to the behavior of the Stylish web extension?

Answer №1

Setting run_at to document_start

If you want to use a manifest.json content_script entry and have the JavaScript run at document_start, you can specify it like this:

  "content_scripts": [
    {
      "matches": ["http://mywebsite.com/*"],
      "js": ["script.js"],
      "run_at": "document_start"
    }
  ]

When your JavaScript runs at document_start, you'll need to append the <style> to the document.documentElement since the head and body aren't yet available at that time.

Also, ensure your match pattern in the matches array includes a path. I've added /* to your pattern.

Using a css entry for static styles

If you're adding static CSS, it's better to move it into a separate .css file and load it automatically through a content_scripts css entry:

manifest.json:

  "content_scripts": [
    {
      "matches": ["http://mywebsite.com/*"],
      "js": ["script.js"],
      "css": ["myStaticStyles.css"],
      "run_at": "document_start"
    }
  ]

myStaticStyles.css:

html {
    background-image: url("http://i.imgur.com/eWtfMME.png");
    background-repeat: repeat;
    background-color: black; 
}

Considerations for network requests

When using a background-image with a network URL, there might be a delay between inserting the CSS and displaying the image. You can address this by simplifying the image, reducing its size, or converting it to a data URL.

If another background-image on the page loads faster, you can prevent it by modifying the HTML, canceling the request with a webRequest.onBeforeRequest listener, or modifying the CSS being loaded.

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

Moving your cursor over the text will eliminate the border of the <img> located directly above it

Check out the latest products here! <ul class="products"> <li class="product first"> <a href="http://www.gwendolynbarnes.com/product/finis/"> <img width="117" height="150" src="http://www.gwendolynbarnes.co ...

JavaScript - Unexpected fluctuations in variable values

After studying Japanese language, I decided to try my hand at experimenting with JavaScript by creating a simple FlashCard game for a project. The game generates an array of random numbers, fills the divs with 6 possible choices using jQuery, randomly sele ...

The "a" HTML link element is stubbornly resisting being attached to an event listener

I have implemented the MutationObserver observer in my program to monitor the addition of elements. One specific condition I am checking for is if the added element is an anchor tag (tag="a") and if the link is a DOI, then I attach a contextmenu ...

Having trouble with Angular JS's ngRoute feature not functioning properly

I've been struggling with my ngRoute implementation. I seem to be unable to load the 'ngRoute' module for some reason. Whenever I run this code, I just end up with a blank page. Below is my app.js file: var app = angular.module('tutor ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Ensure that there is no overlapping of margins when setting the explicit height of the outer

I am curious about the reason behind this phenomenon. The inner div has a margin-bottom of 16px. From what I understand, when the outer div is in contact with the inner div without any padding or border, and the outer div does not have a set height in it ...

Ways to condense a text by using dots in the middle portion of it

How can I dynamically shorten the text within a container that varies in width? The goal is to replace the strings between the first and last words with dots so that it fits within the container. For example, Sydney - ... - Quito. It should only replace wh ...

What could be the reason for NPM failing to work following an update?

Just two days ago, I updated NPM and now it's suddenly not working on my Windows 10 20H2 platform. Every action I take results in the same error message: C:\Users\ethan>npm internal/modules/cjs/loader.js:883 throw err; ^ Error: Canno ...

Automatically populating fields in Laravel 8 after selecting a value from a dropdown menu

Having an issue once again.. If I choose the Banjarmasin-Jakarta route, the shipping cost field will be filled with 1.750.000 However, if I want to select "search shipping route" again, the shipping cost field will be filled with 0 Select "search shippi ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

Ensure that your JQuery code only runs after Angular has completed its rendering

As a newcomer to Angular JS, I may have a question that seems silly. Despite seeing it discussed in several SO questions, I still couldn't figure it out. My goal seems simple, yet I've had a tough time achieving it. I'm attempting to execut ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

The agent.add() function is malfunctioning, while console.log() is functioning properly

I'm currently working on integrating a bot using Telegram, Dialogflow, and Firebase. One particular function that I'm struggling with is as follows: function findDoc(agent){ const userId = request.body.originalDetectIntentRequest.payload.dat ...

JQuery functions for click and hover are not functioning as expected on a div element

I am having trouble with a div that I have declared. The click event is not working as expected, and I also need to use the :hover event in the css, but it isn't functioning either. What could be causing this issue? <div id="info-button" class="in ...

Incorporating full-screen viewing in the browser, these websites provide a seamless user experience with a "learn more" button strategically placed at the bottom. This button effortlessly

Have you ever noticed how websites like Heroku.com and dropbox.com automatically display a full-screen homepage tailored to your browser size? They have a clever button at the bottom that smoothly scrolls you down the page for more information. Have you wo ...

Enhancing User Experience on Android Devices: Automatic Website Zoom-In Feature for Responsive Design

For the first time, I am delving into creating a responsive website design. I seem to be encountering difficulties when it comes to smartphones. I have been using the following meta-tag to ensure that the website loads "zoomed in". (I found this method on ...

Is it possible for a Vue data property to have a value that is determined by another Vue data property object?

Within my HTML form, I have implemented the flatPickr (calendar picker) component which generates an input field. I am currently exploring how to dynamically change the class of the input field if the error class function returns true. Below is the flatPi ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...