3
votes

i have specific theme css which is required only when popup window is launches, nowhere else i'm using that css. Simply loading at the launch of website launch is waste.

Is there a way to load css only when required i.e upon opening popup window i can load the stylesheet?.

4
You could load it from the codebehind of the aspx page displayed in your popup (cfr this answer), or (but it's less clean) put the bit of CSS inside styletags in your aspx.Laurent S.

4 Answers

10
votes

Create a new element like this

var lnk=document.createElement('link');
lnk.href='path/sheet.css';
lnk.rel='stylesheet';
lnk.type='text/css';
(document.head||document.documentElement).appendChild(lnk);

Hope this helps.

1
votes

You might want to try this approach How to load up CSS files using Javascript? (the code below)

But it does add a significant amount of stuffing to the site, maybe the CSS takes up less space anyway?

var $ = document; // shortcut
var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!$.getElementById(cssId))
{
    var head  = $.getElementsByTagName('head')[0];
    var link  = $.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://website.com/css/stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}
1
votes

Add this in your code behind using GetWebResourceUrl

HtmlLink css= new HtmlLink();
css.Href = Page.ClientScript.GetWebResourceUrl(this.GetType(), "yourstyle.css");
css.Attributes["type"] = "text/css";
css.Attributes["rel"] = "stylesheet";
Page.Header.Controls.Add(css);

Or

Literal cssFile = new Literal() 
          {Text = @"<link href=""" + page.ResolveUrl("~yourstyle.css") + @"""  
            type=""text/css"" rel=""stylesheet"" />" };
page.Header.Controls.Add(cssFile);
0
votes

You can do this the jQuery way:

$('head').append("<link rel='stylesheet' href='/href' type='text/css' anythingelse='value' />");