I am trying to convert my app to asynchronous javascript loading with:
<%= javascript_include_tag "application", async: true %>
The problem is that any page-specific scripts are being run before Jquery is loaded asynchronously. How can I defer those until the application.js manifest file has been loaded.
I tried wrapping my page js in $(window).load(function(){});
but this did not help. I still see the following error:
Uncaught ReferenceError: $ is not defined
Update:
This seems to be working for me, but I'd like someone to confirm that it is the correct approach:
<%= javascript_include_tag "application", async: true, onload: 'pageScripts()' %>
Then the page script like:
<script>
function pageScripts() {
// do something
}
</script>
I am trying to convert my app to asynchronous javascript loading with:
<%= javascript_include_tag "application", async: true %>
The problem is that any page-specific scripts are being run before Jquery is loaded asynchronously. How can I defer those until the application.js manifest file has been loaded.
I tried wrapping my page js in $(window).load(function(){});
but this did not help. I still see the following error:
Uncaught ReferenceError: $ is not defined
Update:
This seems to be working for me, but I'd like someone to confirm that it is the correct approach:
<%= javascript_include_tag "application", async: true, onload: 'pageScripts()' %>
Then the page script like:
<script>
function pageScripts() {
// do something
}
</script>
Share
Improve this question
edited Mar 7, 2016 at 15:33
Abram
asked Mar 7, 2016 at 15:15
AbramAbram
41.9k28 gold badges138 silver badges186 bronze badges
1
-
Why not simply write your javascript inside a
window.onload
scope ? – jayant Commented Aug 16, 2016 at 10:44
1 Answer
Reset to default 17Your approach is correct however I would suggest to limit your Async only for production since in development Sprockets hasn't concatinated all of the files yet.
<%= javascript_include_tag "application", async: Rails.env.production?, onload: 'pageScripts()' %>