views:

311

answers:

2

I have written an external script that needs to run after DOM is ready (or after onload if thats impossible).

I use this method to load the script dynamically since I need parameters on the script:

<script type="text/javascript">
document.write(unescape("%3Cscript src='mydomain.com/script.js.php?u="+encodeURIComponent(window.location.host)+"' type='text/javascript'%3E%3C/script%3E"));
</script>

To start the script on time I use cross browser methods to attach the dom ready or onload events.

My question: Can I assume that DOM is ready when my script runs and run my script immediately or that DOM is not ready, and attach to DOM ready event (OR document load)?

If I cannot assume for sure either, my question is how can I tell if DOM is already ready (on the different browsers) when my script runs? In this case the methods to start the script on DOM ready or document load events will not work because the events were already fired.

Notes: 1.I have no control on the web sites the script will be attached to. 2. Can't use Jquery or other library.

+2  A: 

You can be almost sure that dom is not ready yet.

This is a good reference to get this working as you want.

I would either:

1) Load dynamically that script and then attach function to onload even to call/do whatever you want with that off-site .js .

2) Load the script only after DOM is ready.

Maiku Mori
A: 

Put the script near the end of the body of the document. Anything above will be available when your script is invoked (because the browser will have to have parsed it to see your script tag; QED).

Note that other resources (like images or frames) can still be loading at that time.

Aaron Digulla