How to attach jQuery in Drupal 8 Controller

jQuery file can be added to the controller in the following way:

In the controller, file make sure that library defined in libraries.yml is returned along with the markup,

return [
      '#type' => 'markup',
      '#markup' => '<div id="my_js_application"></div>',
      '#attached' => ['library' => ['example_module/example_library']]
    ];

In the libraries.yml, the example_library has to be defined.

example_library:
  version: 1.x
  js:
    js/myapp.js: {}

dependencies:
    - core/jquery

 

Now in myapp.js use the following syntax :

(function ($, Drupal) {

}(jQuery, Drupal));