Embed Javascript in the DOM

I am trying to dynamically insert some js into a DOM element to execute. However, if I embed in $(document).ready(), the script is not evaluated (but entered correctly). Also, if I try to embed as the DOM is loading, the container element does not exist yet. I tested hard-coding script tags in a container and this works great. Is there a way to insert js into a DOM element and evaluate it when the DOM is ready or when the page loads?

$(document).ready(function(){
    var container = document.getElementById('container_div');
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.appendChild(document.createTextNode('[script]'));
    container.appendChild(script);
    //I've also tried .insertBefore and
    //.parentNode.insertBefore and jQuery .append()
});

Am I trying to do this?

+3
source share
1 answer

In pure javascript:

var s = document.createElement('script');
s.setAttribute('src','js/myscript.js');
document.body.appendChild(s);

jQuerify "" jquery , firebug, script.

+1

All Articles