Add defer attribute to javascript_include_tag Rails
Asked Answered
M

2

44

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>

Morpheme answered 11/6, 2012 at 14:43 Comment(0)
F
53
<%= javascript_include_tag "blah.js", :defer => "defer" %>

This will get you (in development):

<script defer="defer" src="/assets/blah.js" type="text/javascript"></script>
Floss answered 11/6, 2012 at 15:21 Comment(4)
For those interested, here is the link to the docs: w3.org/TR/html4/interact/scripts.html#edef-SCRIPTFloss
This also works great with middleman which also uses sprokets / asset pipeline.Agoraphobia
Strange, they don't have any example of async and difer in APIDoc :\Frosty
A bit simpler, same result: <%= javascript_include_tag "blah.js", defer: true %>Vaccination
A
36

You can also do

<%= javascript_include_tag "blah.js", defer: true %>

which is more consistent with other switches.

Accelerant answered 12/1, 2017 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.