I load my custom JavaScript file the following way:



I put:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/Module/etc/module.xsd">
        <script src="js/custom.js"/>

And it works!

However, the custom.js script is loaded at the bottom of the <head> tag. How can I load custom.js to be the first script loaded? Thanks for any help.

  • order doesn't matter for scripts included in the <head> tag. the browser will wait for all scripts to load before it starts executing anything. Nov 22, 2018 at 5:36
  • It's not for something in the body. I need to load some polyfills needed by the rest of scripts. I know it can be done, I just haven't been able to do it.
    – GTS Joe
    Nov 22, 2018 at 5:38

2 Answers 2


Remove the head tag from default_head_blocks.xml

Try to include your js file into default.xml


   <script src="js/custom.js"/>

just add above had the tag before the body tag

Run below commands

php bin/magento cache:clean && php bin/magento cache:flush

  • Doesn't work. It is still not the first JS file included! A bunch of other scripts are first. mixins.js, requirejs-config.js and require.js. I need custom.js to be the top JS file.
    – GTS Joe
    Nov 22, 2018 at 5:20
  • In my case it display in head tag
    – Hitesh
    Nov 22, 2018 at 5:21
  • try this way <link src="js/custom.js"/> maybe it help
    – Hitesh
    Nov 22, 2018 at 5:25
  • It displays, but not the first.
    – GTS Joe
    Nov 22, 2018 at 5:34

Create your custom module and load your script.

Try the following code


var config = {
    deps: ['Anshu_Js/js/custom-js']

The path for custom-js.js would be app/code/Anshu/Js/view/frontend/web/js/

Here Anshu is the namespace and Js is my custom module name.

Here I am loading my javascript module on every page before any other module is loaded by declaring global require js dependency using deps.

I am hoping that this will serve the purpose functionality point of wise.

  • I want to load my JS file from app/design/frontend/nameSpace/magento-luma-child-theme/web/js/custom.js. How do I do it?
    – GTS Joe
    Nov 22, 2018 at 6:05
  • @GTSJoe Then write code of requirejs-config.js file your theme's requirejs-config.js file that will be the same. Nov 22, 2018 at 6:15
  • How? Can you show me? I've never used require-config.js before.
    – GTS Joe
    Nov 22, 2018 at 7:02
  • you can add requirejs-config.js in app/design/frontend/NameSpace/ThemeName/Magento_Theme/ Nov 22, 2018 at 10:01
  • I have no module, I just created a custom theme. How can I create one?
    – GTS Joe
    Nov 22, 2018 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.