简体   繁体   English

替代将样式表加载到头部

[英]Alternative to loading stylesheet into head

谁能告诉我在尝试动态加载样式表时将样式表加载到head的替代方法,我该怎么做?

You can load them dynamically. 您可以动态加载它们。 See here . 这里

There are different implementations for this (you can Google, "load css dynamically", but the basic principle is the same: using JavaScript, you create a link element, give it the appropriate attributes, and append it to the head. 对此有不同的实现方式(您可以Google进行“动态加载CSS”,但是基本原理是相同的:使用JavaScript,您可以创建一个link元素,为其提供适当的属性,并将其附加到头部。

Here's a simple example taken from: 这是一个简单的例子,摘自:
http://otaqui.com/blog/1263/simple-script-to-load-css-from-javascript/ http://otaqui.com/blog/1263/simple-script-to-load-css-from-javascript/

var head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
head.appendChild(link);


Here's a more complex, but robust example, taken from the yepnope library. 这是来自yepnope库的更复杂但更可靠的示例。
https://github.com/SlexAxton/yepnope.js/blob/master/plugins/yepnope.css.js https://github.com/SlexAxton/yepnope.js/blob/master/plugins/yepnope.css.js

This solution allows for a callback (after you load the CSS, do this...) 此解决方案允许回调(在加载CSS之后,执行此操作...)

another alternative is using jquery, try this: 另一种选择是使用jquery,请尝试以下操作:

$('head').append('<link rel="stylesheet" type="text/css" href="style.css">'); 

hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM