I'm trying to get some JavaScript in the head on a single CMS page in Magento 2 and cannot figure it out. I understand how to extend layouts to include this, but I don't want the script on all pages that use a layout. Unfortunately this script does have to be loaded before the page body loads for it to work.

In Magento 1, I simply added this to the Layout Update XML:

<reference name="head">
    <block type="core/text" name="blockname">
        <action method="setText">
                <![CDATA[<script type="text/javascript">

However, that doesn't work in Magento 2.

Is there any way to do this? It seems so simple, yet I've hit a wall trying to figure it out.

By the way, been a long-time lurker, and you guys are great.


  • Did you try admin side
    – Magento 2
    Nov 17 '16 at 17:45

If you use a cms site, you can create a cmsyourname.phtml. Now you can insert your jquery in the top of the file.

In your cms page in the backend, you have to add this:

{{block class="Magento\Framework\View\Element\Template" name="cmsyourname" template="Magento_Cms::html/cmsyourname.phtml"}}

  • Hi Irv, Thanks, I'll give that a try. Where would the phtml file get placed in the directory structure? Would it be under Magento_Cms/templates in our theme? Nov 21 '16 at 16:20
  • Hiho, yea that's it!
    – Irv
    Nov 23 '16 at 13:39
  • Example: app/design/frontend/Theme/Themename/Magento_Cms/templates/html/**YOUREFILEHERE**
    – Irv
    Nov 23 '16 at 13:41
  • @CorLiving_Web did that help you?
    – Irv
    Nov 23 '16 at 15:28
  • Hi Irv, I don't think that worked. It's not that I'm trying to load jquery, I'm trying to add some custom functions. Thanks for your help, but I think I'll just have them load for every CMS page and not worry about having them only on 1 page. Dec 5 '16 at 15:36

I went about doing this a different way. Maybe it's not possible the way I wanted it done.

I actually ended up scripting a CURL to pull the CMS page and just insert the javascript that I wanted in between comment placeholders. I realize this is terribly inefficient, but I could not figure out how else to just get a small JS function added to a single CMS page in Magento.

If anybody else knows how to accomplish this, I welcome a solution

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.