Magento 2 Add JavaScript with Tag Attribute From Block File

If you are looking for a way to include JavaScirpt with a tag attribute from the block file in Magento 2 then this blog post shows you exactly what you are looking for. Sometimes the JavaScript link is different as per admin config values. Also, JavaScript has different data tag values as per admin config values, at that time, this is the best way to include JS from the Block file to the front end.

Below is how to add dynamic Javascript with attributes in Magento 2

<?php
namespace Dhairvi\Demo\Block;

class IncludeJs extends \Magento\Framework\View\Element\Template
{
    protected function _construct()
    {
        $attributes = ['attributes' => ['data-key' => '123456789']];
		
		$this->pageConfig->addRemotePageAsset(
			"https://javascript_url_here.js",
			'js',
			$attributes
		);
    }
}

You can call this block in the head of any XML file and that Javascript will get added with attribute tags in your Magento front-end.

Personally, I use this method in many Magento 2 payment gateway extensions. The JavaScript data tag values are different for sandbox and production modes, so this method helps me a lot in this case.