Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I load external stylesheets on request?

$.getScript('ajax/test.js', function() {   alert('Load was performed.'); }); 

.. like the above code which loads an external JS on request, is there something similar available to load an external CSS stylesheet when required?

Like for example when I use lightboxes (inline popups) on my site, I want to avoid loading lightbox JS and CSS files onload, unless requested by the user.

Thanks

like image 919
eozzy Avatar asked Jan 24 '10 07:01

eozzy


People also ask

Is it possible to include an external stylesheet in another stylesheet?

Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword.

How do you add a stylesheet externally to the code?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.

How are external stylesheets used?

External CSS With an external style sheet, you can change the look of an entire website by changing just one file! Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.


1 Answers

Yup: if you create a <link> tag linking to a stylesheet and add it to the <head> tag, the browser will load that stylesheet.

E.g.

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

However, as per @peteorpeter’s comments, this doesn’t work in IE 8 or under — there, you need to either:

  1. append the <link> before setting its href; or
  2. use IE’s document.createStyleSheet() method

Also, checking whether a link has already been added doesn’t work reliably across all browsers.

I would also question part of your premise:

I want to avoid loading lightbox JS and CSS files onload, unless requested by the user.

Why? To reduce page weight? I can understand the desire, but you should measure the size of your CSS and JS files (after minification and gzipping) with the lightbox code in there, and without, to see whether the reduction is worth:

  1. the added complexity of loading on-demand; and
  2. the slightly reduced responsiveness of the lightbox (because when loading on-demand, the lightbox will have to wait for its own CSS and JS to load before it can do its thing)

After minification and gzipping, there may well not be that much difference.

And bear in mind that you can instruct the browser to cache your CSS and JS for a long time, meaning it only gets downloaded when a user visits your site with an empty cache.

like image 133
Paul D. Waite Avatar answered Sep 22 '22 01:09

Paul D. Waite