7

I want to add the following link in the head tag, but its returning 404 error. Can anyone help me on this?

<script  type="text/javascript"  src="https://www.google.com/recaptcha/api.js"></script>
20

I'd recommend using the script method rather than the text method, it's easier for other developers to understand, it's less code, and meets Magento's official instructions.

To do this use the same script or link XML as normal but include src_type="url". As noted in the official docs

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="https://www.google.com/recaptcha/api.js" src_type="url"/>
    </head>
</page>

Results

enter image description here

  • Did not know you could specify a src_type on the script tag until now :) – Smartie Mar 4 '16 at 17:40
  • How to add script with parameter? <script src="//maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places" src_type="url" /> – Sunny Khatri May 30 '18 at 8:23
  • & not accepting with script tag in magento 2 – Sunny Khatri May 30 '18 at 8:26
3

If you are adding this globally, the easiest way is to do it through the admin area.

Go to Stores > Configuration > Design and then in the HTML Head tab you can add miscellaneous scripts.

You can add it using xml though. For example, if you just wanted it to be added to your homepage, put the following in the layout file view/frontend/layout/cms_index_index.xml inside your custom module.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="https://www.google.com/recaptcha/api.js" src_type="url"/>
    </head>
</page>

As a side note, if you can avoid putting the js in the head i would as this will case render blocking until the js has been fully downloaded.

  • i need only in one custom page. – Sivakumar K Mar 4 '16 at 10:29
  • That kind of information is useful to know at the start :) I will update my post. – Smartie Mar 4 '16 at 11:06
  • The action tag has been depreciated, please see devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/… for more info. – Ben Crook Mar 4 '16 at 16:22
  • How to add script with parameter? <script src="//maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places" src_type="url" /> – Sunny Khatri May 30 '18 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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