In my web app I inject some user specific data into the html page.
It looks like this in the page source
<body>
<script>
var userData = {};
window.GLOBAL = {
userData: userData
};
userData.user = {'user_hash': 12478999584505 };
</script>
<script src="/static/scripts/myapp.js"> </script>
Inside myapp.js
I retrieve the user_hash
and call an initialisation function:
init(window.userData.user.user_hash);
A few users experience this problem spuriously:
Cannot read property 'user_hash' of undefined
It turns out it is very hard for me to pinpoint the exact cause of the problem. This error never happen to me in either production or development environment. There is also no error on the server side that indicates the user_hash
generation has failed. I have tried to reproduce this error by throttling network speed in Chrome via Dev Console etc but I haven't been able to trigger this error yet.
On the user side, the platforms vary from mobile devices (could be running the latest version of iOS or andriod) to desktop, and different browsers (chrome, firefox or safari). My point is there is no clear pattern I can pin it down to a particular platform or brower version.
I speculate that the exception happens if /static/scripts/myapp.js
is loaded and executed before window.GLOBAL
is properly initialised, this exception will be fired.
I am thinking of adding defer
keyword to the myapp.js
script tag, based on this answer.
My questions are:
1) Is there any issue with my current HTML markup? (the two script tags)
2) My hypothesis is basically that these two script tags may have some racing condition between them. Does it stand?
3) Can adding defer
attribute to the second script tag potentially fix this issue if answer to question 2 is yes?
4) If answer to question 3 is no, what else I can try?