Changing Order of JavaScript Files in Head – Magento 2

javascriptlayoutmagento2requirejs

I add a custom JavaScript file with the following code:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="VendorNamespace_Module::someJs.js"/>
    </head>
</page>

My problem is that this js file requires jQuery, but it is loaded before the jQuery JavaScript file (when I look at the head section of my html, jQuery.js comes after someJs.js). How can I change this order so that my file is loaded afterwards?

Best Answer

You don't need to change the order. you just have to declare that your script depends on jquery.
Make your someJs.js file look like this

define([
    'jquery'
    //you can add here any other dependencies you have
], function($) {
    ...your file content here
});

[EDIT]
If the js is from an source you cannot modify, like a third party module you can just create your own module that contains a js file with this content

require([
    'jquery',
    'VendorNamespace_Module/someJs'
]);

then include that file in the layout instead of VendorNamespace_Module/someJs.js.
This should load jquery before the vendor js.

But on the side note...if you got a third party module that has a js file that does not start with require or define then it might be something wrong with the module.

Related Topic