locked
Conditional scripts.render possible? RRS feed

  • Question

  • User2108892867 posted

    Hello everyone. I have a C# web application (not MVC).  I have this piece of code:

    <asp:PlaceHolder ID="PlaceHolder1" runat="server">
        <%: Scripts.Render("~/bundles/lib/angular")%>
    </asp:PlaceHolder>

    This code will load angualarjs library to my page. However, because this code is on a webuser controller, so when I drop it on an aspx page, sometimes I have a warning that I am trying to load the library more than once. Is there a way to check if the angularjs library has already existed? If it does, don't load it again? 

    thanks. 

    Monday, September 23, 2019 1:48 AM

All replies

  • User61956409 posted

    Hi asplearning,

    This code will load angualarjs library to my page. However, because this code is on a webuser controller, so when I drop it on an aspx page, sometimes I have a warning that I am trying to load the library more than once. Is there a way to check if the angularjs library has already existed? If it does, don't load it again? 

    If you'd like to check if a specific js library is loaded, and dynamically load it conditionally from WebUserControl, you can try the following approach.

    In WebUserControl, check if the existence of specific js library, such as 'Scripts/angular.min.js', and dynamically call jQuery.getScript() to load script libraries.

    <asp:PlaceHolder ID="PlaceHolder1" runat="server">
        <%--<%: System.Web.Optimization.Scripts.Render("~/bundles/lib/angular")%>--%>
    </asp:PlaceHolder>
    
    <script>
        var len = $('script').filter(function () {
            console.log($(this).attr('src'));
        return ($(this).attr('src') == 'Scripts/angular.min.js');
    }).length;
    
    if (len === 0) {
        $.getScript('/bundles/lib/angular');
    }
    </script>
    
    <div ng-app="">
     
    <p>Input something in the input box:</p>
    <p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
    <h1>Hello {{name}}</h1>
    
    </div>

    In .aspx page, if not add reference to "Scripts/angular.min.js", the above code will help add scripts and make Angular functionality work well.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <%--<script src="Scripts/angular.min.js"></script>--%>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <uc1:WebUserControl1 runat="server" ID="WebUserControl1" />
                <input type="button" value="clickme" onclick="myfunc()" />
            </div>
        </form>
    </body>
    </html>

    Test Result

    With Regards,

    Fei Han

    Monday, September 23, 2019 7:49 AM