1

I know this question has been already addressed here but that workaround does not work in my case.

I have a function in an external JavaScript that I would like to call immediately after the page is loaded. This is the snippet in the external code to be executed

var user_id = "";
var obj = obj || {};

obj.Id = {
    assignId : function(id) {
        console.log(id);
        user_id = id;
        window.alert("ID no:" + user_id);
        return user_id;
    }
}

and this is the HTML

<script>
obj.Id.assignId("a string");
</script>

I also tried this way

<script>
window.onload = function() {obj.Id.assignId("a string");}
</script>

but window.onload is called afterwards in the external file so I think it was overridden as described in this question. Here is what I get from the console in both previous cases:

Uncaught ReferenceError: obj is not defined

When using this way:

window.onload = function() {
    obj.Id.assignId("UA-0001");

}

I don't get any error but the function is not triggered though.

What I'm not able to figure out is: if prompting directly in the console obj I get Object {Id: Object} and if prompting obj.Id.assignId("a string") I get exactly what I want.

Is there any explanation for this?

6
  • plnkr.co/edit/Km81qCnz9ayn0YfG8pgK?p=preview I just copy pasted your code into plunker and it works as expected. External scripts are first, and then execution of the function from external script Commented Jun 27, 2017 at 9:53
  • Thanks, but in a real context, e.g. a website, it does not work. Commented Jun 27, 2017 at 12:54
  • This is a real context, you must have a racing condition where this function is called before script is loaded, that's why it works when you run from console Commented Jun 27, 2017 at 12:56
  • I'm printing some console log and seems that the script is loaded first, and then the function is called later. Commented Jun 30, 2017 at 15:00
  • Is it possible that script and the execution of the function have different context/scope? Commented Jun 30, 2017 at 15:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.