r/JavaScriptTips • • Jan 12 '23

Conditionally load scripts included in HTML by manipulating the type attribute

Post image
7 Upvotes

1 comment sorted by

1

u/Low_Mammoth_9371 Jan 12 '23

Code to copy:


if (conditional === true) {

const cScripts = document.querySelectorAll('.conditional');

cScripts.forEach((item) => {

const script = document.createElement('script');

const attrs = item.getAttributeNames();

attrs.forEach((attr) => {

script.setAttribute(attr, item.getAttribute(attr));

});

script.type = 'text/javascript';

script.async = false;

item.remove();

document.head.appendChild(script);

})

}