Magento – Magento 2 Add javascript to single page

javascriptlayoutmagento-2.1magento2

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">
            <text>
                <![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.

Thanks.

Best Answer

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"}}