Loading external Javascript in Drupal 8

posted in: Drupal, Javascript | 0

Javascript files that are hosted in the cloud or external Javascript files can be loaded using the libraries similar to internal javascripts in Drupal 8.

Following is the example of mark, hosted in the cdnjs .  Add the following library definition to libraries.yml file. only type: external property is needed to mention it is an external javascript file. Other options can be used as needed.

hello_js_external:
    js:
        https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.es6.js: {
            type: external,
            minified: false,
            attributes: {
                defer: true, 
                async: true
                },
            }
    dependencies:
        - core/jquery

 

Add the following in the routing.yml file to define a path that loads external javascript.

hello_js_external: 
    path: "hello_js/external"
    defaults:
        _controller: Drupal\hello_js\Controller\HelloJsController::external
    requirements:
        _permission: 'access content'

 

Load the javascript with #attached attribute in the Controller

namespace Drupal\hello_js\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloJsController extends ControllerBase {

    
    public function external() {
        return[
            '#title' => 'This is example for external Javascript',
            '#type' => 'markup',
            '#markup' => $this->t("This is an exmple to show external Javascript Loading"),
            '#attached' => array(
                'library' => array(
                    'hello_js/hello_js_external',
                )
            )
        ];
    }

}

 

IF you access hello_js/external and if you look at the source, you’ll see external Javascript is loaded successfully in Drupal 8 website.

Loading external Javascript is similar to loading internal Javascript file in Drupal 8

Leave a Reply