Question

I'm trying to get TestService.Server.WWW_SERVER_URL, but TestService.Server is undefined. When I call test1(), it works well. But I cannot access the object literal TestServer. Is there a different way?

test.html

<script type="text/javascript" language="javascript" src="TestService.js"></script>
<script type="text/javascript" language="javascript">
    function test() {
        alert("TestService.Server.WWW_SERVER_URL[" + TestService.Server.WWW_SERVER_URL + "]");
        //test1();
    }
</script>

TestService.js

document.write("<scr" + "ipt type='text/javascript' src='TestServer.js'><" + "/scr" + "ipt>");

var TestService = {
    Server: TestServer,
    Delimiter: ""
};

function test1() {
    test2();
}

TestServer.js

var TestServer = {
    WWW_SERVER_URL: "http://www.test.com"
};


function test2() {
    alert("test2 has been called!");
}
Was it helpful?

Solution

You have this in your TestService.js

document.write("<scr" + "ipt type='text/javascript' src='TestServer.js'><" + "/scr" + "ipt>");

var TestService = {
    Server: TestServer,
    Delimiter: ""
};

you are trying to set a property in TestService with TestServer which hasnt loaded yet as you do not give time for the newly added script to load

TestService.Server will evaluate to undefined since TestServer does not exist yet

Setup an onload function that will add your script and then set your TestService.Server variable when its loaded

var TestService = {
    Server: null,
    Delimiter: ""
};

function test1() {
    test2();
}

window.onload = function() {
    var head = document.querySelector("head");
    var script = document.createElement("script"); 
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "TestServer.js");

    head.addEventListener("load", function(event) {
        if (event.target.nodeName === "SCRIPT"){
            TestService.Server = TestServer;
        }
    }, true);

    head.appendChild(script); 
}

OTHER TIPS

If you attach scripts dynamically, IE, Firefox, and Chrome will all download the scripts in an asynchronous manner.

Firefox and Chrome will wait till all of the async requests return and then will execute the scripts in the order that they are attached in the DOM but IE executes the scripts in the order that they are returned over the wire.

source

In your case, you can't gurantee TestServer.js get executed before TestService.js. So I will recommend you change the way you access global variable cross-file.

You can add TestServer.js to your html right before TestService.js, so they can execute one by one.

Anyhow, it is NOT recommended to do stuff like this, you can wrap them in your own namespace. Plus you'd better check the variable you want to use cross-file whether it's undefined before you use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top