Magento – How to load js file first in Magento 2

javascriptknockoutjsmagento2requirejs-config.js

I'm using Magento 2 and I have a js file that was called like this:

default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
      <referenceContainer name="after.body.start">
          <block class="Vendor\Module\Block\Ajax\Login\Js" template="Vendor_Module::login-ajax.phtml" name="login.ajax" as="login.ajax" before="head.components" ifconfig="loginpopup/general/enabled" />
      </referenceContainer>
    </body>
</page>

login-ajax.phtml

<script type="text/x-magento-init">
{
    "*": {
        "vm/loginajax"    : <?php echo $block->getJsOptions(); ?>
    }
} 

requirejs-config.js

var config = {
    map: {
        '*': {
            'vm/loginajax': 'Vendor_Module/js/login-ajax'
        }
    }
};

Vendor_Module/js/login-ajax

define([
    'jquery',
    'mage/translate',
    'jquery/ui',
    'mage/validation/validation',
    'vm/mycustom'
], function ($, $t) 

the js file size is 3KB , i noticed the js file is rendered not at the very beginning, how can i set the priority so this js file will load first?

Best Answer

You cannot manually manage the sort order of JS files within core Magento 2 to the level you are asking for, and even if you could you do not want your file to load first as you have dependencies:

'jquery',
'mage/translate',
'jquery/ui',
'mage/validation/validation',
'vm/mycustom'

You have to wait until your dependencies have loaded else you will just run into a lot of errors. If for some reason you really do want your file to load first then do not use Require JS at all.

Related Topic