We have a Rails application where we are including our application dependencies in the html head within application.js
:
//= require jquery
//= requi
As others have described, you are loading scripts and then trying to execute code before your scripts have finished loading. Since this is an occasionally intermittent error around a relatively small amount of code located in your HTML, you can fix it with some simple polling:
(function runAnalytics () {
if (typeof analytics === 'undefined') {
return setTimeout(runAnalytics, 100);
}
analytics.track('on that awesome page');
}());
... the same can be used for other libraries, hopefully you see the pattern:
(function runJQuery () {
if (typeof $ === 'undefined') {
return setTimeout(runJQuery, 100);
}
$(document).ready(...);
}());
Edit: As pointed out in the comments, the load
events would be better suited for this. The problem is that those events might have already fired by the time the script executes and you have to write fallback code for those scenarios. In favor of not writing 10+ lines of code to execute 1 line, I suggested a simple, non-invasive, quick and dirty, sure to work on every browser polling solution. But in order to not get any more downvotes, here's a more proper tedious and over complicated solution in case you have some beef with polling: