ali
ali

Reputation: 11045

JavaScript load script dynamically inside a DIV

I have created a DIV dynamically and I want it to contain a JavaScript link, that will output something on it. The JavaScript link source is absolute. Obviously, this doesn't work:

var div = document.createElement('div');
    div.id = 'mydiv';
    div.innerHTML = "<script type='text/javascript' " + 
                    "src='http://mydomain.com/myscript.js'></script>";
    document.body.appendChild(div);

so I tried this one

var script = document.createElement('script')
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'http://mydomain.com/myscript.js');

var div = document.createElement('div');
    div.id = 'mydiv';

    div.appendChild(script);
    document.body.appendChild(div);

In my script file I have a simple alert('Testing...'); code. The problem is that it doesn't work. The script inclusion is typed inside the div (I see it when I inspect the DIV in Chrome), but it doesn't work. I don't see the 'Testing...' message. What am I missing or doing wrong? Thanks!

Upvotes: 0

Views: 3637

Answers (2)

Dhiraj
Dhiraj

Reputation: 33618

The way i understand it, your code does not wait till the DOM is ready.

It is advised to use jquery's ready which will ensure that the script passed to it runs only after the DOM is ready

Hope this helps

Upvotes: 1

Jashwant
Jashwant

Reputation: 28995

<html>
<head>  
</head> 
<body>  
<script type='text/javascript'> 
    var script = document.createElement('script')
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'my.js');

    var div = document.createElement('div');
    div.id = 'mydiv';

    div.appendChild(script);
    document.body.appendChild(div); 
</script> 
</body>
</html>

This code works for me, But yes, document.write() does not work for me.

Upvotes: 0

Related Questions