Explain Codes LogoExplain Codes Logo

Can scripts be inserted with innerHTML?

javascript
prompt-engineering
security
performance
Anton ShumikhinbyAnton Shumikhin·Jan 7, 2025
TLDR

Scripts won't be executed when inserted using innerHTML as the browser does not evaluate script tags added this way. Consequently, you need to programmatically create and append a <script> element:

var script = document.createElement('script'); script.text = 'console.log("Hello World. Yes, we still do this!");'; // ;) Old school style document.body.appendChild(script);

For greater flexibility in script execution, you could use eval(), jQuery 1.6+, MooTools, or document.createElement. These methods carry their own benefits and downsides, with security being a paramount aspect to keep in mind.

Different methodologies to parse and execute scripts

Execution via eval()

eval() allows direct execution of inline scripts. However, before use, sanitize input to prevent XSS attacks. Be cautious, eval() affects performance and its use should be wise:

eval('console.log("eval() is calling for troubles. Use sparingly");'); // Shhh... Don't tell anyone we used eval() here!

Custom-built function for script execution

A custom function like nodeScriptReplace() can extract and execute scripts from an innerHTML string. This offers a controlled way to handle such cases:

function nodeScriptReplace(node) { if (nodeScriptIs(node) === true) { node.parentNode.replaceChild(nodeScriptClone(node), node); // Switch and bait! } else { var i = -1, children = node.childNodes; while (++i < children.length) { nodeScriptReplace(children[i]); } } return node; }

Script tag creation using DOM methods

Methods like document.createElement('script') offer a cross-browser solution to create executable script elements. For instances where innerHTML is used with script tags, adopt appendChild or insertBefore to ensure the scripts are executed.

Performance implications

Frequent dynamic execution of scripts can affect performance, so be mindful of your design decisions.

Other scripting techniques

Alternative tools like document.createContextualFragment parse HTML strings and can execute scripts, bringing more options to the table.

Security precautions

To plug vulnerabilities and combat XSS attacks, always sanitize content. Libraries like DOMPurify can help safeguard content security.

Browser and library compatibility

Check compatibility when relying on libraries. For instance, jQuery 1.6+ can handle and execute script tag insertion.

Cross-browser execution

Ensure scripts execute across Firefox, Chrome, and other browsers. Rely on recognized methods to avoid compatibility pitfalls and quirky browser behaviors.