Search code examples
javascriptjquerygreasemonkeyscript-tag

Can't append a script to head


var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://www.mydomain.com/bleh.php';
script.id = 'rawr';
$('head').append(script);
alert($('#rawr').attr('src'));

That returns null. Why is this?


Solution

  • You can use the regular .appendChild() instead:

    $('head')[0].appendChild(script);
    

    http://jsfiddle.net/PeaqH/

    What this will do is access the first <head> element on the page and then use the regular DOM child append. As far as why the method you tried didn't work, I'm not sure... I have to think about it, although I suspect it has something to do with how jQuery handles adding script elements to the page.