5

Is there a way to set async defer on a <script> tag with the built in:

{% includeJsFile %}

It's for Google Maps e.g.:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>

I'd still like to be able to output this at the bottom of the layout from within another template. Is this possible?

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
alexr
  • 608
  • 4
  • 11

3 Answers3

8

As of Craft 3 (Tested using RC5) you can do it like this:

{% do view.registerJsFile("path/to/script.js", {"async":"async", "defer":"defer"}) %}

Source: Documentation for Yii's view.registerJsFile()

stojda
  • 163
  • 1
  • 8
4

Not as of Craft 2.6.2791.

If that's a requirement for you, you can not use that tag and put a block in your footer and manually create the script tag with async defer set.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
  • thanks for the feedback Brad - i'll look in to an alternative way of implementing it. – alexr Jun 19 '16 at 12:40
  • @alexr how did you implement this in the end? I am currently at the same conundrum. – Terry Upton Oct 23 '17 at 16:21
  • @TerryUpton i think in the end i ended up manually putting it in the footer of my site in an if statement. In this particular site I was setting a title var in each template in twig anyway, and only had a map on one page, so i ended up doing something like {% if title == 'mappage' %}{% endif %} – alexr Oct 26 '17 at 15:17
1

Knowing that <script>s are imploded with \n char. You can add async defer this way:

{%- set scripts = getFootHtml() | split("\n")  -%}
{%- for script in scripts -%}
    {%- if script matches "%\/assets\/js\/main\.js%" or ' src=' not in script -%}
        {{- script | raw -}}
    {%- else -%}
        {{- script | replace('script type', 'script async defer type') | raw -}}
    {%- endif -%}
{%- endfor -%}