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>
Yes, you can use both attributes but you need to use defer or async, not both. For more see the comparison and use one based on your need. defer attribute: First it will download the script file and then wait of html parsing. After the end of html parsing, script will execute.
Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.
If a third-party script is slowing down your page load, you have several options to improve performance: Load the script using the async or defer attribute to avoid blocking document parsing. Consider self-hosting the script if the third-party server is slow.
The async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously as soon as it is available. Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).
Your 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()' %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With