5

I'm wanting to add some JavaScript to the bottom of every page, but I don't want to add it to the layout(s), so I'd like a way of doing it with a pipeline (or similar).

I've tried a few of the MVC pipelines, and within there I've used Sitecore.Context.ClientPage.ClientScript.RegisterClientScriptBlock(). The code runs with no errors, but the page never has the script added. Perhaps it's a timing thing with the order of the pipelines, I don't know.

Has anyone had any luck with doing this sort of thing before? How can it be done?

2
  • 5
    I don't have an answer for you, but just as a comment... I've seen similar approaches before and it is really hard to debug. Front-end issues that the front-end team can't find because it's buried in a pipeline in the server-side code makes fixing bugs a pain. I usually recommend keeping your presentation stuff as much in the presentation layer as possible. Mar 26, 2018 at 2:37
  • Why you don't want to / can't include javascript to layout? I am with @JayS. This shouldn't be hard-coded in the code behind. It should be part of footer component or another rendering that will be placed in footer Mar 26, 2018 at 11:36

1 Answer 1

1

Short answer:

  • Yes, it can be done via mvc.getPageRendering with some additional processors.
  • But where is the code? It's from Habitat at github

The detail is:

Habitat has implemented this requirement, you can take a view of Assets module in Foundation layer

Configure Pipeline's processors

  1. They added a couple of additional processors into mvc.getPageRendering pipeline through Foundation.Assets.config, e.g. ClearAssets, AddAssets and so on

  2. The implementation of a processor, for example, AddAssets.cs

  3. Then, they leave the task of storing assets for AssetRepository.cs

  4. Eventually, RenderAssetsService.cs is responsible for rendering assets to the view.

How to use

  1. From the module which will be using Foundation.Assets, such as Foundation.Theming (from Habitat), take a look at Foundation.Theming.config, in which they declare the assets which should be rendered when needed.

    • Assets can be javascript or css which will be files or inline (I have not tried with this). enter image description here
    • It's also configured to be rendered for specific or all sites (if you're in multi-sites scenario), because it has been handled in RenderAssetsService.cs enter image description here
  2. To render, let get Default.cshtml from Project/Habitat as our example

    • They can be rendered at Head or Bottom through the lines of code enter image description here

Hope it's useful

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.