What I decided to do is write a ScriptTagHelper that provides an attribute of “OnContentLoaded”. If true, then I wrap the inner contents of the script tag with a Javascript function to execute once the document is ready. This avoids the problem with the jQuery library having not loaded yet when the ViewComponent’s script fires.
[HtmlTargetElement("script", Attributes = "on-content-loaded")]
public class ScriptTagHelper : TagHelper
{
/// <summary>
/// Execute script only once document is loaded.
/// </summary>
public bool OnContentLoaded { get; set; } = false;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!OnContentLoaded)
{
base.Process(context, output);
}
else
{
var content = output.GetChildContentAsync().Result;
var javascript = content.GetContent();
var sb = new StringBuilder();
sb.Append("document.addEventListener('DOMContentLoaded',");
sb.Append("function() {");
sb.Append(javascript);
sb.Append("});");
output.Content.SetHtmlContent(sb.ToString());
}
}
}
example usage within a ViewComponent:
<script type="text/javascript" on-content-loaded="true">
$('.button-collapse').sideNav();
</script>
There might be a better way than this, but this has worked for me so far.