如何在VueJS(SPA)应用程序上动态加载CSS文件?
短片
然后我需要调用一些东西,通过响应数据加载新的CSS文件。
我们将此用于网站品牌推广(CSS取决于实际域名 - 但网站安装在一个主机上)。此CSS文件可以位于我们的服务器(/assets/css/xx.css)或其他服务器上。
Vue组件的简短摘录:
loadCssRequest(location.href).then(function(reponse){
// something whats load css by response.css_code
});
感谢任何想法。
答案 0 :(得分:1)
您可以将css注入组件头部
loadCssRequest(location.href).then(function(reponse){
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = reponse;
document.getElementsByTagName('head')[0].appendChild(style);
});
或者,如果您在其他服务器上有css路径(例如/assets/css/xx.css
)
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/assets/css/xx.css');
document.getElementsByTagName('head')[0].appendChild(link);