如何使用Javascript加载CSS文件?

本文翻译自:How to load up CSS files using Javascript?

Is it possible to import css stylesheets into a html page using Javascript? 是否可以使用Javascript将CSS样式表导入html页面? If so, how can it be done? 如果是这样,怎么办?

PS 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. 附言:JavaScript将托管在我的网站上,但我希望用户能够在其网站的<head>标签中放置,并且它应该能够将托管在我的服务器上的CSS文件导入当前网页。 (both the css file and the javascript file will be hosted on my server). (css文件和javascript文件都将托管在我的服务器上)。


#1楼

参考:https://stackoom.com/question/2PZI/如何使用Javascript加载CSS文件


#2楼

Call the following function to dynamically load CSS or JavaScript file. 调用以下函数以动态加载CSS或JavaScript文件。

function loadjscssfile(filename, filetype) {
  if (filetype == "js") { //if filename is a external JavaScript file
    // alert('called');
    var fileref = document.createElement('script')
    fileref.setAttribute("type", "text/javascript")
    fileref.setAttribute("src", filename)
    alert('called');
  } else if (filetype == "css") { //if filename is an external CSS file
    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", filename)
  }
  if (typeof fileref != "undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

Pass the complete file path with the name as filename argument. 传递完整的文件路径,并将名称作为filename参数。


#3楼

var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("th:href", "@{/filepath}")
fileref.setAttribute("href", "/filepath")

I'm using thymeleaf and this is work fine. 我正在使用百里香,这很好。 Thanks 谢谢


#4楼

Here's a way with jQuery's element creation method (my preference) and with callback onLoad : 这是使用jQuery的元素创建方法(我的偏爱)和回调onLoad

var css = $("<link>", {
  "rel" : "stylesheet",
  "type" :  "text/css",
  "href" : "style.css"
})[0];

css.onload = function(){
  console.log("CSS IN IFRAME LOADED");
};

document
  .getElementsByTagName("head")[0]
  .appendChild(css);

#5楼

如果使用jQuery:

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

#6楼

Below a full code using for loading JS and/or CSS 下面是用于加载JS和/或CSS的完整代码

function loadScript(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var done = false
  var extension = '.js'
  for (var file of files){ 
    var path = directory + file + extension 
    var script = document.createElement("script")
    script.src = path        
    script.type = "text/javascript"
    script.onload = script.onreadystatechange = function() {
        if ( !done && (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete") ) {
            done = true
            script.onload = script.onreadystatechange = null   // cleans up a little memory:
            head.removeChild(script)  // to avoid douple loading
        }
  };
  head.appendChild(script) 
  done = false
 }
}

function loadStyle(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var extension = '.css'
  for (var file of files){ 
   var path = directory + file + extension 
   var link = document.createElement("link")
   link.href = path        
   link.type = "text/css"
   link.rel = "stylesheet" 
   head.appendChild(link) 
 }
}

(() => loadScript('libraries/', ['listen','functions', 'speak', 'commands', 'wsBrowser', 'main'])) ();
(() => loadScript('scripts/', ['index'])) ();

(() => loadStyle('styles/', ['index'])) ();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值