2

How do i Include static resources (JavaScript, CSS, fonts) before in Magento 2?

i follow the docs magento 2 Include static resources (JavaScript, CSS, fonts)

i have copied the file from base theme to the extended theme

my_extended_theme_dir/Magento_Theme/layout/default_head_blocks.xml

and here is the code:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0" />
    <script id="mcjs">!function(dsds){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://some script.js");    </script>
    </head>
</page>

but no changes, recreated static files, clear cache, reindex... what am i missing?

1

In your app/design/frontend/MODULE/NAME/Magento_Theme/layout/default.xml you can put a following code

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>

    <referenceContainer name="head.additional">
        <block class="Magento\Framework\View\Element\Template" name="head_scripts" template="Magento_Theme::static/head.phtml" />
    </referenceContainer>

    </body>
</page>

Next, create a file Magento_Theme/templates/static/head.phtml and inside you can put a every JS script like e.g Google Analytics or other

Clear the cache and you should see content from head.phtml before close of </head>

1

you can add this code in an phtml file path:

Magento_Theme/templates/html/header/head.phtml

and call that file in default.xml as below

<referenceBlock name="head.additional">
     <block class="Magento\Framework\View\Element\Template" name="head.additional.script" template="Magento_Theme::html/header/head.phtml" />
</referenceBlock>
2
  • it's working this way, it's there a way to add scripts like this before /body tag ?
    – mindsoul
    Jan 8 '18 at 7:34
  • Yes, you have to add the script inside the body tag eg. <body>your script</body>
    – Kajal
    Feb 13 '18 at 13:03

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.