Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add defer attribute to javascript_include_tag Rails

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>

like image 360
varatis Avatar asked Jun 11 '12 14:06

varatis


People also ask

How do you add a defer?

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).

What is the difference between async and defer attributes?

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.

What is async defer in JavaScript?

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.


2 Answers

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

This will get you (in development):

<script defer="defer" src="/assets/blah.js" type="text/javascript"></script> 
like image 130
emrass Avatar answered Sep 23 '22 17:09

emrass


You can also do

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

which is more consistent with other switches.

like image 35
Obromios Avatar answered Sep 23 '22 17:09

Obromios