有个疑问,关于seajs.importStyle的参数为什么是CSS样式字符串而不直接使用外部样式表的路径
dafeizizhu opened this issue · comments
MaiZhiying commented
看了一下seajs.importStyle
的代码,这个方法直接加入一个style
元素,然后把参数中的CSS样式字符串当作是元素内部的textNode插入到style
中。
这里有个疑问,为什么不直接动态加入一个link
,直接设置其href
,然后插入到head
中,类似这样:
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "css/base.css");
link.setAttribute("media", "all");
document.getElementsByTagName("head")[0].appendChild(link);
在打包的过程中相信也可以获取到对应css文件的路径。这样写的话css内部的url
引用就能写相对路径了,而使用style
的话只能写绝对路径。
我写了一些测试代码,在IE6、7、8、9、火狐3.6、24、Chrome最新版本、Safari最新版本、Opera最新版本上都测试过,是没有问题的,代码可以参考这里。
其实就是想请教一下,这里为什么要用style
而不用link
,是不是link
还有其他不为人知的兼容性问题,或者是为了减少一个请求而不使用link
?
afc163 commented
使用 seajs.importStyle,意味着我们没有 css 文件的路径也不打算上传文件。
而且 link 需要下载 css ,会导致一段时间的样式闪烁。
MaiZhiying commented
明白了。根据现在的实现,路径的问题是否只能强制要求在源码中写绝对路径?
afc163 commented
根据现在的实现,不需要写任何路径啊。
seajs.importStyle(".main {color:#000}")
MaiZhiying commented
".main { background-image: url(path/to/image) }"
这种路径……
afc163 commented
嗯,建议都使用绝对路径。