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?

3 Answers 3

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.

3
  • thanks for the feedback Brad - i'll look in to an alternative way of implementing it.
    – alexr
    Commented Jun 19, 2016 at 12:40
  • @alexr how did you implement this in the end? I am currently at the same conundrum. Commented Oct 23, 2017 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' %}<script src="path/to/script" async defer></script>{% endif %}
    – alexr
    Commented Oct 26, 2017 at 15:17
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()

0
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 -%}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.