load css javascript,html - How to load up CSS files using Javascript? - Stack Overflow

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);

}

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

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.

VanillaJS

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:

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 );

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值