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 yourdefault_head_blocks.xml - Remove the
<referenceBlock name="require.js">section from yourdefault.xml(overwriting the corerequire.jstemplate 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\Templateclass since your script doesn't need custom backend logic—your existinghead.phtmltemplate works perfectly here.
Step 3: Verify and Flush Caches
- Clear Magento's layout and full-page caches to apply the changes:
bin/magento cache:flush layout full_page - 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
相关产品推荐
相关产品推荐

