5. Using CSS and JavaScript / CSS和JavaScript的使用

5.1 The theme compiler / 主题编译器

为了方便用户在自定义的theme中使用CSS和JavaScript文件,从而使他们能够自动被Shopware编译器进行压缩。
你需要将你的CSS和JS文件放在用户自定义theme的frontend/_public路径中:

ExampleTheme
└── frontend
    └── _public
        └── src
            ├── css
            │   └── example.css
            └── js
                └── example.js```
接下来,你需要在你自定义的主题中定义要用到的CSS和JS文件。这些配置都可以在你的Theme.php文件中,比如:

**5.1.1 Add CSS files**

protected $css = array(
'src/css/example.css'
);```
5.1.2 Add JS files

protected $javascript = array(
        'src/js/example.js'
  );```

>注意:当用户像上面那样添加了js之后,Shopware默认了用户也有权访问jQuery。在[第七章](https://developers.shopware.com/designers-guide/javascript-statemanager-and-pluginbase/?_ga=1.104502400.143501327.1484905555)中会讲解更多关于用jQuery创建自定义插件的信息。

**5.1.3 Compiling files / 编译文件**
Every time you add changes to your LESS, CSS or JavaScript files the corresponding theme files have to be compiled. There are two ways of doing this.

ProductionAnchor link for: production
During production mode you can start the compiler via the administration panel in the cache and performance module. Go to Configuration -> Caches & Performance -> Caches and check the Compile themes option.

DevelopmentAnchor link for: development
For development you have the option to disable the compiling in Configuration -> Theme Manager -> Settings -> Disable compiler caching.
But the best way for developing is to use the grunt file watcher.

##5.2 Asynchronous JavaScript / Javascript异步
Since Shopware 5.3 we are loading the concatenated JavaScript file asynchronously. This improves the first rendering of the page also known as page speed. If you are using the compiler you should not worry about a thing, because your script is loaded together with all other Shopware scripts.

If there is a reason for you to implement your script in a different way, please be aware of possible race conditions that could occur. When you need some parts from the main script as a dependency (for example jQuery) there is a new callback method which you can use to wait for the main script to load.

document.asyncReady(function() {
    // do your magic here  
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容