noobcoder noobcoder - 1 year ago 55
jQuery Question

how to inject script into document <head> without jquery

I am building a browser extension and I have a function inside of

tags that modifies the DOM that I need to inject into the
of any given webpage. The entire function is a string(
"<script>function content blah blah</script>"
). I was using jquery to achieve this:


and this works fine. I would like to remove jQuery for a few reasons but when I try to create a
element to inject into the
with vanilla javascript everything fails. I have tried two methods so far:


var headSelector = document.querySelector('head');
var el = document.createElement('div');
el.innerHTML = modFunction;
modFunction = el.firstChild;
headSelector.insertBefore(modFunction, headSelector.firstChild);

document.head.insertAdjacentHTML('afterbegin', modFunction);

Both javascript attempts inject a
tag with the correct function into the
, however, neither executes the function. Not sure why jQuery is working and the vanilla javascript doesn't. Any help would be greatly appreciated. Thanks

Answer Source

You have a few mistakes.

  1. If your modFunction is a string that contains <script> tag before and after it, your code won't work, because changing innerHTML of div will not execute added scripts.

  2. Using insertAdjacentHTML function is unneccesary, because modFunction is now object of type Text, which will insert [object Text] string before your script.

  3. Instead, use appendChild function to insert properly new script element into head.

Although @Jantho1990 said that it is better to load script from file instead, many browsers use cache, so if you change your script source, it wont be always visible in browsers.

var scriptSource = '//YourScriptSource.....';
var scriptElem = document.createElement('script');
scriptElem.text = scriptSource;