动态加载样式表 [英] Dynamically load stylesheets
问题描述
我知道你可以在页面的头部有样式表,但我喜欢把它们在一个单独的文件。现在我正在使用单页应用程序。
i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i'm working with a single page application.
在SPA中内容是动态的,对吗?所以我不想导入所有的样式表在头部分与链接标记。我可以以某种方式导入样式表,当我需要他们吗?
Well in an SPA the content is dynamic, right? so i didn't want to import all the style-sheets in the head section with the link tag. Can i somehow import style-sheets as-and-when i need them?
我的意思是,我可以有一个链接在身体,动态内容,样式表也得到加载?这样我不必加载所有的样式表,即使动态内容没有加载..
I mean, can i have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that i dont have to load all the stylesheets even when the dynamic content is not loaded..
我再次强调:每当内容加载,样式加载
I stress again: Whenever the content loads, the styles load.
我知道我可以在内联样式的帮助下这样做:
I know i can do it with the help of an inline style like this:
~PSEUDO CODE
<tagname style="somestyle"></tagname>
但是我也可以有一些动态文件导入?我可以在身体的链接
标签吗?
but can i have some dynamic file imports too? Can i have the link
tag in the body too? Even if it works, is it standard?
推荐答案
您应该查看异步加载资源,例如着名的google-analytics代码。您可以使用Javascript加载外部样式表。
You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.
JavaScript
(function(){
var styles = document.createElement('link');
styles.rel = 'stylesheet';
styles.type = 'text/css';
styles.media = 'screen';
styles.href = 'path/to/css/file';
document.getElementsByTagName('head')[0].appendChild(styles);
})();
第1行和第7行为变量创建一个新范围,使局部变量不会与全局作用域变量。没有必要只是一个最佳实践。此解决方案还假设您在HTML中有一个< head>
标记。
Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a <head>
tag in your html.
这篇关于动态加载样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!