Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3403656
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T05:17:15+00:00 2026-05-18T05:17:15+00:00

Looking for an elegant way of having scripts added once on a page and

  • 0

Looking for an elegant way of having scripts added once on a page and that’s it.
I have a partial view that requires 2 CSS files and 2 JS files. In most places, there is only need for 1 of the partial views. On a single page though, I need 3 of these same partial views, and each partial view has the 4 files, so I have 6 JS links and 6 CSS links. Quite ugly.

I original idea was to use jQuery to see if the tags (by id) are existant on the page yet or not. If they aren’t, then add them in. Otherwise, do nothing. This was going to be an inline script like….

<script type="text/javascript" language="javascript">
     function(){
           var jQueryUICSS = $("#jQueryUICSS");
           if(!jQueryUICSS){
                document.write('link id="jQueryUICSS" href="/Content/smoothness/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />')
           }
           ...And so on for the other 3 tags.
 };

But, I’m not sure that will work (or will the lead dev accept it):P

Any other ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T05:17:16+00:00Added an answer on May 18, 2026 at 5:17 am

    David,

    I use a couple of static htmlhelpers in my code for exactly this scenario. it works on the principle that the context.items collection gets populated per request and therefore if an item exists in the context.items collection then it doesn’t get added twice. anyway, enough of the scottish words of wisdOOOm, ‘yill jist be waantin the coade’…

    for our Scripts:

    public static MvcHtmlString Script(this HtmlHelper html, string path)
    {
        var filePath = VirtualPathUtility.ToAbsolute(path);
        HttpContextBase context = html.ViewContext.HttpContext;
        // don't add the file if it's already there
        if (context.Items.Contains(filePath))
            return MvcHtmlString.Create("");
    
        // add the beast...
        context.Items.Add(filePath, filePath);
    
        return MvcHtmlString.Create(
            string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", filePath));
    }
    

    for our cuddly css:

    // standard method - renders as defined in as(cp)x file
    public static MvcHtmlString Css(this HtmlHelper html, string path)
    {
        return html.Css(path, false);
    }
    // override - to allow javascript to put css in head
    public static MvcHtmlString Css(this HtmlHelper html, 
                                    string path, 
                                    bool renderAsAjax)
    {
        var filePath = VirtualPathUtility.ToAbsolute(path);
    
        HttpContextBase context = html.ViewContext.HttpContext;
        // don't add the file if it's already there
        if (context.Items.Contains(filePath))
            return null;
    
        // otherwise, add it to the context and put on page
        // this of course only works for items going in via the current
        // request and by this method
        context.Items.Add(filePath, filePath);
    
        // js and css function strings
        const string jsHead = "<script type='text/javascript'>";
        const string jsFoot = "</script>";
        const string jsFunctionStt = "$(function(){";
        const string jsFunctionEnd = "});";
        string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
        string jsBody = string.Format("$('head').prepend('{0}');", linkText);
    
        var sb = new StringBuilder();
    
        if (renderAsAjax)
        {
            // join it all up now
            sb.Append(jsHead);
            sb.AppendFormat("\r\n\t");
            sb.Append(jsFunctionStt);
            sb.AppendFormat("\r\n\t\t");
            sb.Append(jsBody);
            sb.AppendFormat("\r\n\t");
            sb.Append(jsFunctionEnd);
            sb.AppendFormat("\r\n");
            sb.Append(jsFoot);
        }
        else
        {
            sb.Append(linkText);
        }
    
        return MvcHtmlString.Create( sb.ToString());
    }
    

    usage in both cases:

    <%=Html.Css("~/Content/Site.Css")%>
    <%=Html.Script("~/Scripts/default.js")%>
    

    have fun…

    [edit] – pay particular attn to the comment line:

    // this of course only works for items going in via the current
    // request and by this method
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking for an elegant way to remove all files in a folder that
I'm looking for a simple/elegant way to grep a file such that every returned
I am looking for an elegant way to access local files (either on phone
I'm currently looking for a way to load in multiple scripts/plugins without having a
I'm looking for an elegant way to select fields from a view, where a
I'm looking for most elegant way to ajaxify my forms (with jQuery). How do
I'm looking for an elegant way to suppress exceptions when calling a method. I
I'm looking for an elegant way to generate a sequence of the rolling average
I'm looking for an elegant way to use values in a Java enum to
I'm looking for an elegant way to turn this array: Array ( [foo] =>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.