0

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:

requirejs-config.js

Has the following code:

var config = {
 deps: [
 'js/myJS',
 ]
};

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?

asked Nov 26, 2018 at 18:46
2
  • 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. Commented Nov 27, 2018 at 4:03

1 Answer 1

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 ?>
 </head>
 <body data-container="body" data-mage-init='{"loaderAjax": {}, "loader": { "icon": "<?= /* @escapeNotVerified */ $loaderIcon ?>"}}' <?= /* @escapeNotVerified */ $bodyAttributes ?>>
 <?= /* @escapeNotVerified */ $layoutContent ?>
 </body>
</html>
answered Nov 27, 2018 at 4:57
3
  • 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. 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> Commented Nov 27, 2018 at 18:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.