janksmap
janksmap

Reputation: 71

Chrome extension css won't load instantly

I'm writing a Chrome extension that injects a javascript file into a page to change the css at all times. When I go to the website, the modified css always takes a fraction of a second longer to load after the page loads. This might create a bad user experience. I'm not sure if this is possible, but I would like to have it change the css and potentially execute other scripts before the user even sees the page.

Manifest file:

{
    "name": "Some Extension",
    "version": "1.0",
    "description": "Some desription",

    "content_scripts": [
        {
            "css": ["styles.css"],
            "js": ["script.js"],
            "matches": ["https://*.familysearch.org/*"]
        }
    ],
    "manifest_version": 2
}

script.js

    console.log("Extension working");
    let navElement = document.getElementById('primaryNav');
    navElement.style.backgroundColor = 'blue';

Upvotes: 1

Views: 177

Answers (1)

Dai
Dai

Reputation: 155708

By default extensions are loaded into a page when the browser feels like it (run_at: 'document_idle') rather than immediately before the page is loaded (document_start) or immediately before it finishes loading (document_end). Note that these events are unrelated to DOM's load and DOMContentLoaded events.

You need to do two things:

  1. Add "run_at": 'document_start' to your extensions' manifest.
  2. Update your script so it will work before the DOM is loaded (because document.getElementById('primaryNav') will return null because the primaryNav element won't exist yet).

Upvotes: 2

Related Questions