How to make sure JQuery dynamically inject CSS properly and ready to use?
I know that I can do this to inject CSS like this:
$(document).ready(function() {
$("a").click(function() {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
});
But, this async.开发者_JS百科 i.e. even I append the link, there is no guarantee that the css is available at that time. (because of the CSS download) so, if there is another js runs at the same time and try to aasign a class, then 1) Will it still work? Will the css applied later on after the file is fully downloaded?
If not, is there something like a call back or some trick that I can use to know that the css is fully downloaded?
If you need it guaranteed to be loaded and the CSS is definitely on the same domain, you could request the contents via Ajax and then inject the properties directly.
I've had good luck doing this (in iOS at least) by creating a dummy <link>
element in the <head>
and calling text()
on it with the contents of the CSS file (as a string).
For example, roughly:
$("a").click(function() {
$.get('style2.css', function (data) {
$('link').text(data);
// Stuff that must happen after CSS injection here
});
})
But honestly this is a rare use case.
精彩评论