Description
It appears our use of document.write
in the ScriptTagHelper
to dynamically load JS files in to the browser (the CDN fallback feature) causes issues when trying to use Content Security Policy.
It appears this could be somewhat addressed by switching to dynamically creating and appending script
elements to the DOM (assuming the CSP policy that enables inline script blocks is enabled), however that results in the scripts being loaded asynchronously to the page rendering, which potentially causes errors in the page (e.g. if the scripts now run out of order to how they were declared).
This article is a good write-up of the various methods that can be used to load scripts while controlling (or not) their execution order and they're affect on rendering.
We should investigate whether we could enhance the ScriptTagHelper
to better support these techniques, along with CSP, e.g.:
- Have a way to toggle the method used to do the script loading, or just move to dynamically modifying the DOM and ignore the older browsers for which it introduces issues
- Honor the
async
attribute on thescript
element when dynamically loading the fallback script, maybe even use it as part of the download method toggle (always usedocument.write
unlessasync
attribute is explicitly set, or something) - Maybe add a new attribute that forces scripts to be dynamically fetched async but with order preserved by the browser using these techniques, and use it combination with the above
- Support deferring all scripts to the end of the page (or some marker element) where they can then be properly downloaded and executed in order, with fallbacks if necessary, using "all the tricks known to web developer-kind", or something
- Give up and go shopping
Possible example that would render inline JS to do async downloads of the scripts while preserving their declared execution order:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/jquery.min.js"
async asp-preserve-load-order></script>
<script src="~/js/needs-jquery.js" async asp-preserve-load-order></script>