I want to dynamically add a javascript tag, whose src points to an external source, whose
result will generate some other javascript. That javascript will draw external data, a table for football teams.
If I include it with document.write it works fine.
<script type="text/javascript">
var everysport_u="http://puff.everysport.com/team_puff_competitiontable_normal_script_52764:0.html";
document.write("<scr"+"ipt type='text/javascript' charset='ISO-8859-1' src='"+everysport_u);
var everysport_r=Math.floor(Math.random()*99999999999);
document.write("?_r="+everysport_r);
document.write("'><\/scr"+"ipt>");
</script>
Howevery using DOM manipulation it does not.
var script = document.createElement('script');
var everysport_r=Math.floor(Math.random()*99999999999);
var everysport_u = "http://puff.everysport.com/team_puff_competitiontable_normal_script_52764:0.html";
script.src = everysport_u;
script.type = 'text/javascript';
document.getElementById('everysport-accordion').appendChild(script);
The script at http://puff.everysport.com/team_puff_competitiontable_normal_script_52764:0.html is using
document.write. A script which usesdocument.writecan only be included during the loading of the page. After the page loads,document.writeno longer functions as expected.It’s fine to include a script which itself does DOM manipulation with DOM manipulation. But the fact of the matter is
document.writeexpects to be able to write immediately to the document wherever it is located. Trying todocument.writeafter the page has loaded will clear the current page and override it.Check out this simple example: http://jsbin.com/azumus/1/ (and click refresh a few times).
If you do add a script which uses
document.writeto an element higher up in the page during page load, thedocument.writewill write to the page, but not where you intend it to.document.writewill only write where the page is currently loading; it can’t be used to write into any element you want it to.See this page for an example: http://jsbin.com/ayomoz/1/ (and view source).
In summary
Put your
<script>tag wherever you intend to write to the document. If you want to write to the element with ideverysport-accordion, you need to do something like this: