-->

How to use asynchronous (non-blocking) javascript

2020-07-18 11:00发布

问题:

I use DNN's Client Resource Management for loading javascript and css into a theme (skin) this way I can take advantage of minification and composite files but I need them to be asynchronous (non-blocking). How can this be done?

回答1:

So far as I know, there is not a way to use the async (or defer) attribute on the <script> tag that is rendered by the Client Resource Management Framework. You can add an attribute to the <script> (or <link>) tag rendered by the Client Resource Management Framework. Add the attribute HtmlAttributesAsString to the control, and then separate the attribute name and value with a colon, e.g. HtmlAttributesAsString="async:true". One thing to note is that there's a bug where multiple attributes, which are supposed to be allowed via commas, aren't rendered correctly (keep an eye on this pull request which will fix that, and then need to be integrated into DNN).

You can also write your script so that it sets up an event handler to perform an action after the page is loaded (e.g. wrap your code in jQuery(function ($) { … });)

You can also use the ForceProvider property on the DnnJsInclude control to set the script to load at the bottom of the </form> element, instead of towards the top of the <body> (the default for scripts). So, that might look like this:

<dnn:DnnJsInclude runat="server" 
                  PathNameAlias="SkinPath"
                  FilePath="js/theme.min.js" 
                  ForceProvider="DnnFormBottomProvider" 
                  Priority="10000" />