Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inject code into masterpage / html head from a user control

Tags:

asp.net

I am struggling with something that I guess should be standard practice really. I have a number of user controls that use some JQuery plugins. I do not really want to link to the extra CSS and JS files from my main masterpage as this would cause extra load to the user the first time they hit the site, (admittedly it would only be the once), so I was just putting them links into the top of the user control. Then I looked at my source HTML, not nice! Even worse for controls that repeat multiple times on a page.

So I was thinking is there a way of injecting them into the Head of the page when they are needed from the User Control. For that matter is there a way of doing it to the footer for JS stuff?

like image 922
Jon Avatar asked Dec 14 '22 00:12

Jon


1 Answers

To dynamically register a script (and ensure that duplicates are merged) in ASP.NET you can call:

Page.ClientScript.RegisterClientScriptInclude(
    "mykey", "~/scripts/jquery-1.3.2.js");

And read the full details on this method on MSDN.

To add CSS dynamically you can do something like this:

HtmlLink cssLink = new HtmlLink();
cssLink.Href = "path to CSS";
cssLink.Attributes["some attr1"] = "some value1";
cssLink.Attributes["some attr2"] = "some value2";
Page.Header.Controls.Add(cssLink);

This example of injecting CSS will not merge duplicate entries. To avoid duplication you'll have to keep track of duplicates yourself. One place you can store a list of scripts you've already registered is in HttpContext.Items. Stick a HashSet in there that keeps a list of all registered scripts so that you don't register the same CSS file twice (which is generally harmless, but something to avoid anyway).

like image 57
Eilon Avatar answered Mar 04 '23 11:03

Eilon