Naruto
Naruto

Reputation: 9634

Load stylesheet at runtime

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?.

Upvotes: 3

Views: 4900

Answers (4)

Luke Madhanga
Luke Madhanga

Reputation: 7447

You can do this the jQuery way:

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

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

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);

Upvotes: 1

chandaniitr
chandaniitr

Reputation: 185

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.

Upvotes: 11

Alex
Alex

Reputation: 5204

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);
}

Upvotes: 1

Related Questions