如何使用 Javascript 加载 CSS 文件? [英] How to load up CSS files using Javascript?

查看:31
本文介绍了如何使用 Javascript 加载 CSS 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Javascript 将 css 样式表导入 html 页面?如果是这样,怎么做?

Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?

PS javascript 将托管在我的网站上,但我希望用户能够放入他们网站的 <head> 标签,并且它应该能够导入一个 css 文件在我的服务器上托管到当前网页.(css 文件和 javascript 文件都将托管在我的服务器上).

P.S the javascript will be hosted on my site, but I want users to be able to put in the <head> tag of their website, and it should be able to import a css file hosted on my server into the current web page. (both the css file and the javascript file will be hosted on my server).

推荐答案

这是老派"的做法,希望它适用于所有浏览器.理论上,您将使用 setAttribute 不幸的是 IE6 不支持它.

Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute unfortunately IE6 doesn't support it consistently.

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.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);
}

此示例检查 CSS 是否已添加,因此只添加一次.

This example checks if the CSS was already added so it adds it only once.

将该代码放入 javascript 文件中,让最终用户只需包含 javascript,并确保 CSS 路径是绝对路径,以便从您的服务器加载.

Put that code into a javascript file, have the end-user simply include the javascript, and make sure the CSS path is absolute so it is loaded from your servers.

以下示例使用纯 JavaScript 根据 URL 的文件名部分将 CSS 链接注入 head 元素:

Here is an example that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();

var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";

document.getElementsByTagName( "head" )[0].appendChild( link );
</script>

在关闭 head 标记之前插入代码,CSS 将在页面呈现之前加载.使用外部 JavaScript (.js) 文件将导致无样式内容的 Flash (FOUC) 出现.

Insert the code just before the closing head tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js) file will cause a Flash of unstyled content (FOUC) to appear.

这篇关于如何使用 Javascript 加载 CSS 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆