How can I load a custom JavaScript file using RequireJS at the very beginning? Please note: The key is that RequireJS must load my script FIRST, before any other scripts, as the rest of my script depends on that file.

Currently, my:


Has the following code:

var config = {
    deps: [

My file, located in app/design/frontend/Vendor/Theme/web/myJS.js, is working, but it's being loaded AFTER the rest of the RequireJS files. How can I load myJS.js to be the very first file RequireJS loads?

  • so is the rest of your script in another js file? Commented Nov 27, 2018 at 4:02
  • I need to load it before all of Magento's stock JS files too. It needs to be the very first JS code loaded.
    – GTS Joe
    Commented Nov 27, 2018 at 4:03

1 Answer 1


In your case it's probably easier to overwrite root.phtml instead of using require.js.

Copy default root.phtml from vendor/magento/module-theme/view/base/templates/ to your theme location app/design/frontend/Vendor/Theme/Magento_Theme/templates/. Edit the file to include your script right before or after where require.js is included. It'll look something like this,

<!doctype html>
<html <?= /* @escapeNotVerified */ $htmlAttributes ?>>
    <head <?= /* @escapeNotVerified */ $headAttributes ?>>        
        <script type="text/javascript" src="path/to/your/custom.js"></script>
        <?= /* @escapeNotVerified */ $requireJs ?>
        <?= /* @escapeNotVerified */ $headContent ?>
        <?= /* @escapeNotVerified */ $headAdditional ?>
    <body data-container="body" data-mage-init='{"loaderAjax": {}, "loader": { "icon": "<?= /* @escapeNotVerified */ $loaderIcon ?>"}}' <?= /* @escapeNotVerified */ $bodyAttributes ?>>
        <?= /* @escapeNotVerified */ $layoutContent ?>
  • hi @subroutines, can you check this magento.stackexchange.com/questions/251362/… Commented Nov 27, 2018 at 6:06
  • This is what I wanted, thank you! But how do I get the base URL so I can link to my file? I tried <?php echo $this->getBaseUrl(); ?> but it doesn't work. Linking directly yields a 404 error.
    – GTS Joe
    Commented Nov 27, 2018 at 15:13
  • I got it! I was able to insert my script at the top by overriding root.phtml as you suggested then, right after <head>, putting: <script type="text/javascript" src="<?php echo $this->getViewFileUrl( '/' ); ?>/js/myJS.js"></script>
    – GTS Joe
    Commented Nov 27, 2018 at 18:59

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.