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?