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:
- append the
<link>
before setting its href
; or
- 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:
- the added complexity of loading on-demand; and
- 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.
link
statement in$()
just uselightbox_stylesheet = '<link ... />'
and the.append()
call will do what is needed. You generally don't want to wrap anything in a jQuery object that cannot be contained in adiv
. – Xanthe