I am attempting to inject vue
into a page from a content script before other scripts run. I have the framework saved as a file in my extension directory and I can inject it with this code:
let s = document.createElement('link');
s.as = 'script';
s.rel = 'preload';
s.href = chrome.runtime.getURL('vue.min.js');
document.documentElement.insertBefore(s, document.documentElement.firstChild);
The content script is run at document_start
, so I would expect it to inject this script into the DOM before it is even built and so be the first script to load. This is not true:
It's loaded later. And even though it has the higher priority it still runs after the script even if I set the script to defer
and vue
is finished loading way before. Why does this happen and is there any way to ensure my script loads/executes first?
Loading a separate script file via a URL puts it into the shared queue so it competes with the page scripts, see https://crbug.com/634381.
The only solution is to use a
script
element withtextContent
as a literal string (example: see method 2). And of course the content script should be declared with "run_at": "document_start" in manifest.json.If your code is big, in order to keep it maintainable you would want to use a separate file naturally so you can configure your webpack (or whatever else) and use a special placeholder in the content script which will be then replaced with a literal string containing the file text.