JavaScript and stylesheet tags
You can bundle JavaScript and stylesheet assets with section
, block
and, snippet
files using the following Liquid tags:
Including assets with the relevant files can help you keep the theme modular, making the files portable across different themes and shops without losing their functionality or styling.
If reusability isn't a concern, then you can place the JavaScript or CSS styles that your file needs in your theme's assets
directory and include them using the asset_url
filter with either the script_tag
filter or stylesheet_tag
filter. If an asset has already been included in a parent layout or template, then you don't need to include it again.
Liquid isn't rendered in {% javascript %}
or {% stylesheet %}
tags. Including Liquid code in these tags can cause syntax errors, or prevent styles from being applied to the theme.
Anchor to javascriptjavascript
To include JavaScript, use the {% javascript %}
tag:
Each file can only have one {% javascript %}
tag. Having more than one will result in a syntax error when editing your theme code.
Shopify concatenates the content from {% javascript %}
tags across all section, block and snippet files into one file per file type:
- sections:
scripts.js
- blocks:
block-scripts.js
- snippets:
snippet-scripts.js
These files are then injected into the theme through the content_for_header
Liquid object and asynchronously loaded through a <script>
tag with the defer
attribute.
The content from each {% javascript %}
tag is wrapped in a self-executing anonymous function so that any variables are defined within a closure, and runtime exceptions won't affect other sections.
Anchor to Instance specific JavaScriptInstance specific Java Script
Bundled assets are only injected once for each section, block or snippet file, not for each instance of that file. If you need instance-specific JavaScript, then add data attributes to your section markup and reference those attributes in your JavaScript. For example:
/sections/slideshow.liquid
Anchor to stylesheetstylesheet
The {% stylesheet %}
tag can be used to include CSS styles:
Each file can only have one {% stylesheet %}
tag. Having more than one will result in a syntax error when editing your theme code.
The content from {% stylesheet %}
tags across all sections, blocks and snippets is concatenated into a single styles.css
file by Shopify, and then injected into the theme through the content_for_header
global Liquid object.
Anchor to Instance specific stylesInstance specific styles
Bundled assets are only injected once for each section, block or snippet file, not for each instance of that file. If you need instance-specific CSS, then use an inline <style>
tag.