What is the proper way to add Amazon oneTag code to Drupal 8. Instructions say to add it before the ending body tag.

I think it should be loaded to the /theme.libraries.yml. Here is the code I am trying to add:

<div id="amzn-assoc-ad-123456789"></div><script async src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789"></script>

Do I need to create a file onelink.js with this code? Then reference it in libraries?



It's actually pretty well documented: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#external

MYTHEME.libraries.yml (or MYMODULE.libraries.yml)

    //z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789: { type: external, attributes: { async: true } }

MYTHEME.theme (or MYMODULE.module)

function MYTHEME/MYMODULE_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'MYTHEME/amazon-onetag';

Now we could start to discuss what is "the proper way"?

As Amazon wants it directly before the closing body tag (which is irrelevant in my experience) and as they also put a nice container with an ID around the script (which very likely is irrelevant as well) you could also simply copy the whole snippet into your (custom or sub-)theme's html.html.twig directly before the closing <body> tag.

But that would at the same time take this script a little bit out of Drupal's influence to handle, preprocess and order all scripts according a desired logic. And it can become a little bit more difficult to maintain in the end.

  • How would one do this in a module? – user1359 Nov 8 '19 at 19:28
  • 1
    @user1359 – Exactly the same. Libraries YAML and the hook. – leymannx Nov 8 '19 at 19:34

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.