javascriptdom-eventsunobtrusive-javascript

Best way to signal my JS script is loaded


I have a JS script that will be hosted on my server and that others will embed in their html, i.e.

...<code for http://yoursite.example.com />
<script type="text/javascript" src="http://mysite.example.com/awesome.js" />
...<code for http://yoursite.example.com />

My script declares an object with a bunch of properties accessible for use as a Javascript Object(), i.e.

<script type="text/javascript">
//From http://mysite.example.com/awesome.js
alert(Awesome.Name);
</script>

Due to the load time variance, it seems I need to signal that the "Awesome" object in my script is ready. I need this to stand on its own, so no dependencies on specific JS frameworks.

Do I need to publish my own custom JS event, or does the simple fact that my script is loaded get captured by one of the existing page-level events? How else should I be doing this?

UPDATE: as a point of reference, if I include the JS in an HTML page running from http://mysite.example.com, the Awesome object is available and populated. When the JS file is included from another domain, the object is undefined at runtime.


Solution

  • The javascript content of <script> tags is executed procedurally, so this

    <script type="text/javascript" src="http://mysite.com/awesome.js" />
    <script type="text/javascript">
        alert(Awesome.Name);
    </script>
    

    will only alert the contents of Awesome.Name if found in any previous script tag.

    To understand if everything has been fully loaded on the page, you have to use the DOMContentLoaded, for firefox, and "onreadystatechange" for ie. Also you can simply check the load event on the window object if you don't care about checking the DOM (could be easier).

    if ( document.addEventListener ) {
        document.addEventListener( "DOMContentLoaded", function(){
             doSomething();   
        }, false );
    } else if ( document.attachEvent ) { // IE        
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                doSomething();
            }
        });
    }