Load external libraries in a custom block I need to implement a custom block using JavaScript. These are the steps I took.


I created a custom module
I created a custom block by creating a class which extends blockbase
I created a JavaScript file
I defined a library in libraries.yml file and included the JavaScript file
I attached the library to the block using #attached


So far so good. In the JavaScript file, I am trying to use the open source Datatables library, but I am unable to add it.

This is the code that implements the block.

/**
 * @file
 * Contains \Drupal\custom_cms_blocks\Plugin\Block\TopNewsBlock.
 */

namespace Drupal\custom_cms_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an 'Active forum topics' block.
 *
 * @Block(
 *   id = "top_news_min_block",
 *   admin_label = @Translation("Top News Min Block"),
 *   category = @Translation("Custom CMS blocks"),
 * )
 */
class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' =&gt; 'markup',
      '#markup' =&gt; '&lt;table id="example_table"&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Artist / Band&lt;/th&gt;&lt;th&gt;Album&lt;/th&gt;&lt;th&gt;Song&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;Muse&lt;/td&gt;&lt;td&gt;Absolution&lt;/td&gt;&lt;td&gt;Sing for Absolution&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;',
      '#attached' =&gt; array(
        'library' =&gt;  array(      
          'https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     ); 
  } 

}


Can you explain me how I can include an external JavaScript file in a block?
Libraries don't work like that. You need a yourmodule.libraries.yml and define it there.

There's detailed documentation on https://www.drupal.org/developing/api/8/assets#external. The following is an example of how a library is defined.

angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }


Then, the library that you specify is yourmodule/nameofthelibrary, see https://www.drupal.org/developing/api/8/assets#render-array or any of the other examples on that page.