3

Having looked over the existing D8 documentation on adding JS to the <head> of a page, I'm still not sure how to go about it?

What is the correct way to achieve this on every page for my theme:

<script src="//use.typekit.net/abc0abc.js"></script>
<script>try{Typekit.load();}catch(e){}</script>

Regarding inline JS, from the latest D8 documentation:

In the case of front-end/styling (e.g. hosted font services), the JS belongs in the theme. Put the JS directly in your html.html.twig file. In the case of fonts, this will also allow you to put it right in the place that gives you the best (and fastest) end user experience, because it allows you to prevent a FOUT (Flash Of Unstyled Text) while the font is still loading (fonts loaded through JS must be listed in the HTML before the CSS)!

So, I guess the inline JS goes directly into html.html.twig, but what about the external file?

I have this in my theme files, but it's not adding the external file to any pages:

mytheme.info.yml

libraries:
  - mytheme/typekit

mytheme.libraries.yml

typekit:
  version: 1.x
  js:
    //use.typekit.net/abc1abc.js: { type: external }
  • Here is a good documentation about how to add JS and CSS in Drupal 8 appnovation.com/blog/how-add-js-and-css-assets-drupal-8-theme – Andrew Jul 12 '15 at 19:25
  • 1
    I think the docs are suggesting to put both lines in your html.html.twig. As far as I know it's not possible to add inline JS via the libraries API. If it's loaded on every page I'm not sure it's worth the effort/obscurity to convert it to a render array like in @MrD's answer, or to even use the libraries API. Just paste it in and be done with it, IMO. – Cottser Jul 15 '15 at 12:49
2

For put the library to the header you must user header: true, then:

mytheme.info.yml

libraries:
  - mytheme/typekit

mytheme.libraries.yml:

typekit:
  version: 1.x
  header: true
  js:
    //use.typekit.net/abc1abc.js: { every_page: true }
    js/custom.js: { every_page: true }

js/custom.js:

try { 
  Typekit.load(); 
} 
catch(e) { 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.