You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 2:如何在<head>标签起始后添加自定义脚本

Solution: Add Script Immediately After <head> Tag in Magento

The issue you're facing is that the head.additional container is rendered at the end of the <head> tag (right before </head>), which is why your script isn't appearing right after <head>. Let's fix this with a proper layout adjustment.

Step 1: Clean Up Incorrect Layout Changes

First, remove the code that's not working as expected:

  • Delete the <referenceContainer name="head.additional"> block from your default_head_blocks.xml
  • Remove the <referenceBlock name="require.js"> section from your default.xml (overwriting the core require.js template can break essential frontend functionality)

Step 2: Add the Script to the Start of <head>

Update your Custom/Module/view/frontend/layout/default.xml with this code:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <!-- Render this script as the first element inside <head> -->
        <block class="Magento\Framework\View\Element\Template" 
               name="custom.head.start.script" 
               template="Custom_Module::success/head.phtml" 
               before="-" />
    </head>
</page>

Key Explanation:

  • The before="-" attribute tells Magento to render this block before all other elements in the <head> container, ensuring it appears immediately after the opening <head> tag.
  • We use the core Magento\Framework\View\Element\Template class since your script doesn't need custom backend logic—your existing head.phtml template works perfectly here.

Step 3: Verify and Flush Caches

  1. Clear Magento's layout and full-page caches to apply the changes:
    bin/magento cache:flush layout full_page
    
  2. Load your frontend and inspect the HTML—your script should now be the first content inside the <head> tag.

Notes on Your Existing Code

Your custom Success block and Data helper are unrelated to this head script issue, so you can leave those as-is (they handle checkout success page template logic, which is separate from this task).

内容的提问来源于stack exchange,提问作者Sandip Dutt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:26:54