H.Rabiee
H.Rabiee

Reputation: 4837

Adding javascript within javascript which loads another javascript

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);

Upvotes: 1

Views: 103

Answers (1)

Nathan Wall
Nathan Wall

Reputation: 10674

The script at http://puff.everysport.com/team_puff_competitiontable_normal_script_52764:0.html is using document.write. A script which uses document.write can only be included during the loading of the page. After the page loads, document.write no 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.write expects to be able to write immediately to the document wherever it is located. Trying to document.write after 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.write to an element higher up in the page during page load, the document.write will write to the page, but not where you intend it to. document.write will 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 id everysport-accordion, you need to do something like this:

...

<div id="everysport-accordion">
    <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>
</div>

...

Upvotes: 2

Related Questions