How to attach library to the page in drupal 8?

At first you should add your library via custom module or theme

1. Create custom_module.libraries.yml file in your module folder
2. Put js or css in your module folder
3. Edit custom_module.libraries.yml file and add name of the library and path to your css or js
  1. my_library:
  2. version: 1.x
  3. css:
  4. theme:
  5. style.css: {}
  6. js:
  7. script.js: {}
  8. dependencies:
  9. - core/jquery

After that you can attach your library to pages as you need it

  1. function custom_module_page_attachments(array &$page) {
  2. $page['#attached']['library'][] = 'custom_module/my_library';
  3. }