Can't append a script to head
-
09-03-2021 - |
Question
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?
La solution
You can use the regular .appendChild()
instead:
$('head')[0].appendChild(script);
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.
Autres conseils
Why not use getScript?
Something worth looking into. Run this with Firebug open.
<script src="jquery.js" id="jq"></script>
<title>Untitled Document</title>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
$(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js';
script.id = 'rawr';
$('head').append(script);
console.log($('#jq'));
});
</script>
U will see that jqueryUI is not being shown in HTML tab of firebug but when u look at the Net tab its showing that jQueryui.min file has loaded. Now click on the console tab and expand #jq item. You can see all the options available to you. There is no src or source option. Hope this helped.