Magento2 – How to Change Order of External and Internal JS Files

javascriptmagento2

I'm trying to work with a geo ip API, and have included the JS for it in my default_head_blocks file, however it is being called after my own geoip-api.js file and therefore it's not picking up the Geo location until after my script has run.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="js/modernizr.js" />
        <script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" src_type="url"/>
        <link src="js/geoip-api.js" />

    </head>
</page>

How can I get the external script to be called before my theme file?

EDIT:

I've removed the link from the above code and instead used:

requirejs.config({
    paths: {
        'maxmind': '//js.maxmind.com/js/apis/geoip2/v2.1/geoip2'
    }
});

require(['jquery', 'jquery/ui', 'Magento_Ui/js/modal/modal', 'maxmind'], function($, modal){
    #my code goes here;
});

However it's still running the maxmind JS after my code has run.

Best Answer

You could use the requirejs that is included with magento 2.

/vendor/magento/module-theme/view/frontend/requirejs-config.js

Put a copy of this file in the root of your theme and then add in the files you need.

Guide to requirejs: http://requirejs.org/docs/start.html

Related Topic