Adding async keyword to script tag using HtmlTextWriter

724 Views Asked by At

We are dynamically adding script tags to a page using HtmlTextWriter, which works great. We have a few that need to have async keyword added and I'm not sure how to do it.

I want the tag to look like this.

<script id="my_script"  async   type="text/javascript"  src="myscript.js"></script>

My method that builds the tags look like this.

    internal static void RenderJavaScriptInclude(HtmlTextWriter writer, string      filePath, string Id)
{
    writer.AddAttribute(HtmlTextWriterAttribute.Id, Id);
    writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
    writer.AddAttribute(HtmlTextWriterAttribute.Src, filePath);
    writer.RenderBeginTag(HtmlTextWriterTag.Script);
    writer.RenderEndTag();
}

How can I modify to add "async"?

Much thanks as always,

Rhonda

1

There are 1 best solutions below

0
On

According to the source code of the RenderBeginTag method, any attribute with value equals to null (but not String.Empty) will be rendered without quoted value. So, just call writer.AddAttribute("async", null); before calling of RenderBeginTag.