注入样式标签+角度组件定时

时间:2016-10-26 09:33:37

标签: javascript html css angularjs

我有以下代码:

//load theme
await theme.load('light');

$state.go('viewer');

theme.load加载一个sass文件,编译它,并将其作为样式标记注入,如下所示:

let themeStyles = document.head.querySelector('style#theme');

if(!themeStyles) {
    themeStyles = document.createElement('style');
    themeStyles.setAttribute('id', 'theme');
    document.head.appendChild(themeStyles);
}

themeStyles.textContent = await importer.import('sass/themes/'+theme+'.scss');

这是我的观众状态的模板:

<map></map>
<top-left-menu></top-left-menu>
<loader></loader>

这是我的地图组件:

.component('map', {
    controller: ['$element', MapController]
});

function MapController($element, map) {
    this.$onInit = () => {
        console.log(document.head.querySelector('style#theme').textContent);
        console.log($element[0].getBoundingClientRect())
    }
}

第一个控制台日志按预期打印注入的CSS,但getClientBoundingRect()函数返回width:0和height:0,即使$state.go仅在theme.load返回并且css为已注入我试过$ postLink,同样的事情。尝试将async / await替换为常规承诺(可能是一些奇怪的babel行为),同样的事情。只有~100ms的setTimeout元素才能报告正确的大小。

我想知道这是否与样式和DOM的计算方式有关,或者与角度设置组件的方式有关。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

找到答案 - 通过@import标记加载外部字体,这样就延迟了CSS评估。