A set of Tag Helpers that can capture a script block and render it later in another place.
- Add a reference to a package:
or
PM> Install-Package ScriptCaptureTagHelper
MyGreatProject> dotnet add package ScriptCaptureTagHelper
- Restore packages:
MyGreatProject> dotnet restore
- Register the Tag Helpers in your application's
_ViewImports.cshtml
file:@addTagHelper *, ScriptCaptureTagHelper
Razor sections does not work in partial views or in display templates. This TagHelper will capture a script
block in the partial view or in the display template and render it later on the page.
To capture a script block add capture
attribute to a <script>
tag
<script capture = '<UniqueID>'>
... JS code to capture
</script>
and to render this block in another file, add render
attribute to an empty <script>
block, specifying the same UniqueID
:
<script render = '<UniqueID>'>
</script>
- Capture multiple blocks by passing the same ID.
<script capture='Foo'>
console.log('Foo 1');
</script>
<script capture='Foo'>
console.log('Foo 2');
</script>
later it can be rendered via single script
tag:
<script render='Foo'></script>
which will expand into a script tag that contains content from two captured tags.
2. Control the order in which captured scripts will be rendered by specifying priority
attribute.
This attribute is optional, if not specified block will be rendered as the last one.
3. script
tag attributes are now preserved, which enables the scenario for capturing script reference:
<script capture='InlineCapture' src='some good CDN' integrity='sha256-bla' crossorigin='anonymous'></script>
will be rendered with all attributes as it is.