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?
-
so is the rest of your script in another js file?subroutines– subroutines2018年11月27日 04:02:14 +00:00Commented 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– GTS Joe2018年11月27日 04:03:49 +00:00Commented 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 ?>
</head>
<body data-container="body" data-mage-init='{"loaderAjax": {}, "loader": { "icon": "<?= /* @escapeNotVerified */ $loaderIcon ?>"}}' <?= /* @escapeNotVerified */ $bodyAttributes ?>>
<?= /* @escapeNotVerified */ $layoutContent ?>
</body>
</html>
-
hi @subroutines, can you check this magento.stackexchange.com/questions/251362/…Jafar Pinjar– Jafar Pinjar2018年11月27日 06:06:35 +00:00Commented 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– GTS Joe2018年11月27日 15:13:03 +00:00Commented 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– GTS Joe2018年11月27日 18:59:05 +00:00Commented Nov 27, 2018 at 18:59
Explore related questions
See similar questions with these tags.