概述
本主题讨论了如何定义在一个特定的Magento商店页面上使用哪些JavaScript组件和小工具。
定位JS组件:walkthrough
找到用于指定元素的 javascript:
-
在浏览器中打开商店页面,使用浏览器调试工具,如Firebug(Firefox)或Inspect Element(Chrome),找到该元素的类或ID。
-
选择查看页面源代码。
-
在页面源中找到相应的元素,看看这个元素、它的子元素或父元素上是否有 data-image-init 或 的调用。这些调用包含了脚本的名称,如JavaScript初始化中所述。
-
找到 js 的源文件:
-
在页面源代码的部分,点击链接到 requirejs-config.js 文件。该文件包含Magento RequireJS的配置,从当前主题的所有模块中收集。
或者,你可以从文件系统中打开requirejs-config.js文件: pub/static/frontend////requirejs-config.js
-
在requirejs-config.js的var config = {...}部分,找到需要的脚本名称,并查看其源文件的路径。这个路径是相对于某些目录的,取决于它是否包含模块参考。
- 如果没有指定模块上下文,路径是相对于<theme_dir>/web(当前主题)。如果在那里没有找到该文件,根据assets fallback,会在父主题的web目录下搜索,然后在lib/web(库)目录下搜索。例如,knockoutjs/knockout脚本名称会解析为lib/web/knockoutjs/knockout.js。
- 如果指定了模块上下文,路径是相对于<theme_dir>/_/web(当前主题模块)。如果在那里没有找到该文件,根据assets fallback,它将在父主题文件的相同位置搜索,然后在<module_dir>(模块)目录中搜索。例如,Magento_Catalog/js/list脚本名称会解析为Magento_Catalog/view/frontend/web/js/list.js。
-
Locate JS component: example
As we discussed in the preceding section, you use browser debugging tools to define which JavaScript component or widget is used for an element. An example follows. To find what JS components are used for displaying the main navigation menu in the Luma theme:
Using the Inspect Element feature of the browser, define that the menu section id
is store.menu
:
Search the page source for store.menu
(illustration follows):
We can see that there's a data-mage-init
attribute in the scope of the <div id= "store.menu"></div>
1 data-mage-init='{"menu":{"responsive":true, "expanded":true, "position":{"my":"left top","at":"left bottom"}}}
According to the JS components initialization notation, this means that this code calls menu.js
.
To find the source file of menu.js
, open requirejs-config.js
by clicking the link to it in the section of the page source. The path to menu.js
is specified there as follows:
1 "menu": "mage/menu",
This means we should check for mage/menu.js
the following locations, in the following priority order (according to the assets fallback rules):
<Magento_Luma_theme_dir>/web/js
(current theme JS files)<Magento_Blank_theme_dir>/web/js
(parent theme JS files)lib/web
(library files)
There is no mage/menu.js
in the current theme or parent theme JS files, so the source file for menu component used for the main navigation menu is lib/web/mage/menu.js