Is there some way to add the defer
attribute easily using the javascript_include_tag
helper in Rails?
I.e., is there some easy way to turn
<%= javascript_include_tag "blah.js" %>
into
<script defer src="blah.js"></script>
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
The script with async attribute will be executed once it is downloaded. While the script with defer attribute will be executed after completing the DOM parsing. The scripts loaded with async doesn't guarantee any order. While the scripts loaded with defer attribute maintains the order in which they appear on the DOM.
In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is important. And async is used for independent scripts, like counters or ads. And their relative execution order does not matter.
<%= javascript_include_tag "blah.js", :defer => "defer" %>
This will get you (in development):
<script defer="defer" src="/assets/blah.js" type="text/javascript"></script>
You can also do
<%= javascript_include_tag "blah.js", defer: true %>
which is more consistent with other switches.
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