How to inject JavaScript using JavaScript

Jan 13, 2021 · 1 min. read

Injecting JavaScript by linking to an external JS file

Typically you'd inject Javascript by adding a script tag with the src attribute set, like this:

var head = document.querySelector('head');
var script = document.createElement('script');
script.src = 'https://some-website-you-want-js-from/script.js';
head.appendChild(script);

This could be used to pull in content from a CDN or from your own site.

Injecting JavaScript as a string

There might be a case when you'd like to add JS as a string. Perhaps you're using a POST request to get some data instead of a GET request. Here's an example:

var head = document.querySelector('head');
var script = document.createElement('script');
script.textContent = 'alert("here");';
head.appendChild(script);