I would like to ask could we move these scripts from body
tag to head
tag? Because i want to add the defer attribute for these scripts.
1 Answer
You would need to modify the SxaLayout.cshtml
file to do this. If you look at the file, at the top it gets all the asset links:
@{
AssetLinks assetLinks = AssetLinksGenerator.GenerateLinks(new ThemesProvider());
}
Once it has those, it renders the styles in the head and the scripts just before the body close:
@foreach (string script in assetLinks.Scripts)
{
@Html.Raw(script)
}
</body>
You would first need to move that to the head in the layout. To add the defer attribute is going to require you to modify the AssetLinksGenerator.GenerateLinks
method. If you decompile that method and follow it through, you will see that the <script>
tags are hard coded. For the base themes, the method is called GetLinks
- you can inherit and override that method tho.
These are the decompiled lines:
foreach (string str in result1.Styles.Select<string, string>((Func<string, string>) (link => "<link href=\"" + link + "\" rel=\"stylesheet\" />")))
result.Styles.Add(str);
foreach (string str in result1.Scripts.Select<string, string>((Func<string, string>) (link => "<script src=\"" + link + "\"></script>")))
result.Scripts.Add(str);
Modify that and add your defer attribute in.