How to add external js in Magento 2

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


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.