I am loading jQuery in this way:
function require(url, cb = new Function) {
var s = document.createElement('script');
s.src = url;
// s.async=true;
// ^^^^^^^^^^^^ This is already removed, but the problem still existed.
s.onload = cb;
document.head.appendChild(s);
}
require(jquery_cdn_url, function(){
try {
alert($);
} catch (e) {
ga('send', 'pageview', e);
}
});
The error in the catch
block is not happening all the time. But for some visitors (very small chance) because I tracked this by sending the information to Google Analytics.
In a previous version of this question, the script had the async
attribute. However in the real project, I removed it, and the error still comes up.
Why is this happening? Is there any way to avoid this?
Some further thoughts:
- The Google Analytics code was also loaded this way, so if the
onload
function doesn't work on some user agents, thega()
should also be sending nothing to Google. - I think of a way to avoid this: in the
try ... catch
block, to reload the failed case with a query like "xxx.html?load=sync". Then I do some detection on the server side, if there is aload=sync
query, then I output a code with sync JavaScript tags inline. This sounds like a possible workaround but not perfect because it would require another reload (a lot more wasted network requests) and some server-side programming work amount.