根據您的使用案例,有許多不同的方法可包含用戶端程式庫。 本檔案提供各自的範例和範例 HTL片段。
如果您沒有時間調查最適合您的情況,請在頁面head
元素內放置下列HTL行,加入用戶端程式庫:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @
categories='wknd.base', defer=true}">
${clientlibs.jsAndCssIncludes @ context="unsafe"}
</sly>
這會同時在您的頁面head
中包含CSS和JS,但會將defer
屬性新增至您的JS script
包含,讓瀏覽器在執行指令碼之前等待DOM就緒,進而最佳化頁面載入速度。
包含用戶端程式庫類別的JS和CSS的基本語法(將產生所有對應的CSS link
元素及/或JS script
元素)如下:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @ categories='wknd.base'}">
${clientlibs.jsAndCssIncludes @ context="unsafe"}
</sly>
若要一次對多個用戶端程式庫類別執行相同操作,可將字串陣列傳遞至categories
參數:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @
categories=['wknd.base', 'cq.foundation']}">
${clientlibs.jsAndCssIncludes @ context="unsafe"}
</sly>
人們通常會想要將CSS包含在HTML head
元素中,而JS則包含在body
元素結尾之前。
在head
中,若要僅包含CSS而不包含JS,請使用cssIncludes
:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @ categories='wknd.base'}">
${clientlibs.cssIncludes @ context="unsafe"}
</sly>
在body
結尾之前,若要僅包含JS而不包含CSS,請使用jsIncludes
:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @ categories='wknd.base'}">
${clientlibs.jsIncludes @ context="unsafe"}
</sly>
若要將屬性套用至產生的CSS link
元素及/或JS script
元素,可以使用數個參數:
<sly data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @
categories='wknd.base',
media='print',
async=true,
defer=true,
onload='console.log(\'loaded: \' + this.src)',
crossorigin='anonymous'}">
${clientlibs.jsAndCssIncludes @ context="unsafe"}
</sly>
可傳遞至jsAndCssIncludes
和cssIncludes
的CSS link
屬性:
media
:字串 script
JS屬性,可傳遞至 jsAndCssIncludes
和 jsIncludes
:async
: 布林值defer
: 布林值onload
: 字串crossorigin
: 字串在某些情況下,無論是為了最佳化,還是為了電子郵件或AMP,可能需要將CSS或JS內嵌至HTML的輸出中。
若要內嵌CSS,可使用cssInline
,在此情況下,您必須撰寫周圍的style
元素:
<style type="text/css"
data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @ categories='wknd.base'}">
${clientlibs.cssInline @ context="unsafe"}
</style>
同樣地,若要內嵌JS,可以使用jsInline
,在此情況下,您必須寫入周圍的script
元素:
<script type="text/javascript"
data-sly-use.clientlibs="${'com.adobe.cq.wcm.core.components.models.ClientLibraries' @ categories='wknd.base'}">
${clientlibs.jsInline @ context="unsafe"}
</script>
頁面元件也支援載入開發人員定義的內容感知CSS、JavaScript或中繼標籤。
要完成此操作,請使用下列結構為com.adobe.cq.wcm.core.components.config.HtmlPageItemsConfig
建立內容感知資源:
com.adobe.cq.wcm.core.components.config.HtmlPageItemsConfig
- prefixPath="/some/path"
+ item01
- element=["link"|"script"|"meta"]
- location=["header"|"footer"]
+ attributes
- attributeName01="attributeValue01"
- attributeName02="attributeValue02"
...
+ item02
...
...