TheShun TheShun - 1 year ago 67
HTML Question

Inject external HTML & JS into a page

I'm trying to build some small widgets tools that webmasters can embed in their websites.

Is there any way that the webmaster can simply load this tool by including a script like this?

<script src="http://mysite/widget.js"></script>

I tried to inject it by loading it in AJAX and then do an
on the body, it's working this way but the JS is not executed.

Content to be injected:

<div>one div</div>
<script>alert('some js')</script>


function load(content) {
var $body = document.body,
$div = document.createElement("div");
$ = "widget";
$div.innerHTML = content;

The content variable contains HTML and JS but the JS is not executed when injected.

Answer Source

Since you don't know where you script will be added - to the head or body tag - and consequently when it will be executed, you need to make sure that DOM is ready, so:

 function load(content) {

    if (document.readyState === "complete" || document.readyState === "loaded") {
         // manipulate DOM
    } else {
       document.addEventListener('DOMContentLoaded', function() {
        // manipulate DOM

Also, since scripts elements added using innerHTML don't get executed, you'd have to either use eval or better create a script like that:

var s = document.createElement('script');
s.text = "alert(\"hi\");"

However, there is no point to add <script> tag to execute some script in your template, since your script is already running when you're adding DOM so do all necessary setups there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download