The best way to notify JS script is loading

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.com />
<script type="text/javascript" src="http://mysite.com/awesome.js" />
...<code for http://yoursite.com />

My script declares an object with a bunch of properties available for use as a JavaScript () object, i.e.

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

Due to the variance of the load time, it seems I need to report 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 post my own custom JS event, or is it just the fact that my script is loading, being captured by one of the existing page-level events? How else should I do this?

UPDATE: as a link point, if I include JS in an HTML page launched from http://mysite.com , the awesome object is accessible and populated. When the JS file is included from another domain, the object is undefined at run time.

+3
source share
5 answers

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

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

will only warn content Awesome.Nameif it is found in any previous script tag.

, , DOMContentLoaded, firefox "onreadystatechange" ie. , DOM ( ).

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

script , DOM , , , . DOM , , . , , script , , script, .

+1

window. , :

if (window["Awesome"] != null) { /* do something */ }
+1

). , script ? , , .

). - , , . , , . , , -.

0

:

<script type="text/javascript" src="myfunction.js"></script>
<script type="text/javascript" src="iwannaloadthis.js?onload=executeThis"></script>

, , myfunction.js( iwannaloadthis.js.

, !

0

Source: https://habr.com/ru/post/1703758/


All Articles