简体   繁体   English

如何在JavaScript中插入外部样式表(动态)

[英]How to insert external stylesheet in JavaScript (dynamically)

...with right path. ......正确的道路。

For example. 例如。 I have script called foo.js. 我有一个名为foo.js的脚本。 I'd like to insert stylesheet declaration which I can do with following instruction: 我想插入样式表声明,我可以使用以下指令:

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

Problem : I have to put full path to the stylesheet file. 问题 :我必须将完整路径放到样式表文件中。 So instead of /template/foo.css I have to put: http://hostname/directory/template/foo.css . 所以我不得不把/template/foo.css放到: http://hostname/directory/template/foo.css I can't set it statically beacause script can be placed in different servers and different locations. 我无法静态设置它,因为脚本可以放在不同的服务器和不同的位置。 So it can be: http://foo.com/bar/foo.css or http://foo.com/foo.css . 所以它可以是: http//foo.com/bar/foo.csshttp://foo.com/foo.css

It would be very useful if I can get path of foo.js file on the server. 如果我可以在服务器上获取foo.js文件的路径,那将非常有用。 That would be good enough beacause then I could set stylesheet location based on the javascrpt's file. 那将是足够好的,因为我可以根据javascrpt的文件设置样式表位置。

I've always done: 我一直都这样做:

$('body').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />');

instead of head 而不是

Ahh... sorry I just realised what your problem is. 啊......对不起,我刚刚意识到你的问题是什么。 One strategy is to extract the path of the script from the DOM itself: 一种策略是从DOM本身提取脚本的路径:

$('script').each(function(i,el){
    var path = el.src.match(/^(.+)\/foo.js$/);
    if (path) {
        $('body').append('<link rel="stylesheet" ' +
                                'href="' + path[1] + '/foo.css" ' +
                                'type="text/css" />'
                        );
    }
})

This is a common technique that I use to get the current script url: 这是我用来获取当前脚本url的常用技术:

var scriptUrl = (function() {
  var scripts = document.getElementsByTagName('script'),
      script = scripts[scripts.length - 1];

  return script.src;
})();

It works basically because when the script is being executed, it is the last script tag on the DOM. 它的工作原理基本上是因为在执行脚本时,它是DOM上的最后一个script标记。

You can use window.location and obtain the path from that. 您可以使用window.location并从中获取路径。 For example for this page it is: 例如,对于此页面,它是:

>>> window.location
http://stackoverflow.com/questions/2033742/how-to-insert-external-stylesheet-in-javascript-dynamically

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

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