Dynamically insert inline <script>

| permalink | javascript

Dynamically inserted <script> tag will only run when you append the script element instead of using the innerHTML or insertAdjacentHTML methods to change HTML directly.

So, you can:

// create element directly
let script = document.createElement('script');
script.innerText = 'alert("triggered!")';
document.head.append(script);

// or parse HTML into a documentFragment
let str = '<script>alert("triggered!")</script>';
let range = document.createRange();
let documentFragment = range.createContextualFragment(str);
document.head.appendChild(documentFragment);

Interesting tidbit about jQuery

If you're familiar with jQuery, script tags will automagically run when you append it using jQuery's multiple append methods.

It turns out jQuery detects script tag insertion, grab the script via Ajax by reading the src attribute, and then ran it through eval().

That is a heck of a lot of processing it's attempting on every single append that you probably don't need.

It also means that if you use jQuery Slim script insertion will fail silently because AJAX methods are missing.

It's time like these you both love and hate jQuery for all the magic it does under the hood, hidden away from view.