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>
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>
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>
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.
You can add external js and css file to your page programmatically by event/observer in Magento2
First create events.xml fie in your vendor/moudule/etc:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_generate_blocks_after">
<observer name="custom-name" instance="vendor\module\Observer\AddLink" />
</event>
</config>
then create an observer class in vendor/module/Observer to add link to header of magento 2 page:
<?php
namespace vendor\module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Page\Config;
class AddLink implements ObserverInterface
{
protected $pageConfig;
public function __construct(
\Magento\Framework\View\Page\Config $pageConfig
) {
$this->pageConfig = $pageConfig;
}
public function execute(Observer $observer)
{
if ($this->pageConfig) {
$this->pageConfig->addRemotePageAsset(
'https://example.com/external.js',
'js', // you can use 'css' to add external css to page
['attributes' => ['async' => true]]
);
}
}
}