Magento 2的JavaScript, CSS 等静态资源是在页面配置文件的 <head>配置。
Magento 2商店页面的 <head>
是在app/code/Magento/Theme/view/frontend/layout/default_head_blocks.xml
里设置。 推荐的添加或者移除CSS和JavaScript的方法就是在自定义模板中扩展该文件。下面是参考:
<theme_dir>/Magento_Theme/layout/default_head_blocks.xml
如果是添加外部的资源, src_type="url"
这个属性是必须设置的。
如果是添加Google webfont,必须设置 rel="stylesheet" type="text/css"
,否则不起作用。
可以通过 <link src="js/sample.js"/>
or <script src="js/sample.js"/>
两种方法添加JavaScript文件到模板中。
The path to assets is specified relatively to one of the following locations:
<theme_dir>/web
<theme_dir>/<Namespace>_<Module>/web
Conditional comments are meant to give special instructions for Internet Explorer. In the terms of adding assets, you can add CSS files to be included for a specific version of Internet Explorer. A sample follows:
This adds an IE conditional comment in the generated HTML, like in the following example:
In this example, orange
is a custom theme created by the OrangeCo vendor.
To remove the static resources, linked in a page <head>
, make a change similar to the following in a theme extending file:
app/design/frontend/<Vendor>/<theme>/Magento_Theme/layout/default_head_blocks.xml
Note, that if a static asset is added with a module path (for example Magento_Catalog::js/sample.js
) in the initial layout, you need to specify the module path as well when removing the asset.
CSS和JS的加载顺序直接决定了你设置的样式是否有效,我们可以通过order属性来设置每个CSS和JS的加载顺序,从而更好的控制Magento的样式输出。
<css src="css/override.css" order="100" /> <css src="css/override2.css" order="100" /> <script src="js/override.js" order="100" /> <script src="js/override2.js" order="100" />