We have specific requirement where we want to load only the scripts/css which are required for particular rendering on the page. Those scripts/css need to be loaded in the <head> tag but not in the middle of the page where the rendering is added. The rendering is added in the middle of the page using a placeholder but is it possible to inject the script and link tag based on specific rendering to be added in the header rendering which is part of separate placeholder.


1 Answer 1


There is a shared feature called "Rendering assets" in Sitecore's Habitat demo code. This will enable you to add Javascript and CSS as inline (part of a script inside script tag or css inside style tag) and also as a JS/CSS file to be added from a Sitecore field for specific renderings if they're added in the fields.

Javscript can be placed either in the HEAD tag or inside the BODY tag. Verify the default location where they're inserted once, you can slightly tweak the location easily as per your requirement. You can check the Foundation.Assets project in Habitat - https://github.com/Sitecore/Habitat/tree/master/src/Foundation/Assets/code

Sample : Maps rendering where two js files & CSS are added that will be inserted to the layout as using the method calls - @RenderAssetsService.Current.RenderScript(ScriptLocation.Head) and @RenderAssetsService.Current.RenderScript(ScriptLocation.Body)

enter image description here

And the JS/CSS that is inserted in the layout are as below in Default.cshtml file:

<html lang="@Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName">
  <!-- Latest compiled and minified JavaScript -->
  @RenderAssetsService.Current.RenderScript(ScriptLocation.Head) //scripts added in the field are inserted here
  @RenderAssetsService.Current.RenderStyles() //css added in the field are inserted here
<body class="header-static @(Sitecore.Context.PageMode.IsNormal ? "" : (Sitecore.Context.PageMode.IsExperienceEditor ? "pagemode-edit" : "pagemode-preview"))">
  <div id="main-container">
  @RenderAssetsService.Current.RenderScript(ScriptLocation.Body) //scripts added in the field are inserted here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.