change css link and wait till new css is loaded

前端 未结 6 506
南笙
南笙 2020-12-17 22:48

I wonder whether it\'s possible to change stylesheet link of the loaded document, then wait till the new css is loaded, and then run appropriate js code

thanks for a

6条回答
  •  -上瘾入骨i
    2020-12-17 23:17

    TeaCoder has a good answer to this question over at https://stackoverflow.com/a/35644406/20774.

    Basically use the elements onload method and put the logic you want to happen after the style loads there.

    It's a nice way to use built in DOM capabilities to do it, but the callback syntax is a little awkward. Here is how I did it with Promises:

    const createOnLoadPromise = (htmlElement) =>
      new Promise((resolve) => {
        htmlElement.onload = resolve;
      });
    const link1 = document.head.appendChild(createStyleLink(href1));
    const link2 = document.head.appendChild(createStyleLink(href2));
    await Promise.all([
      createOnLoadPromise(link1),
      createOnLoadPromise(link2),
    ]);
    // do whatever you need to do after the await
    

提交回复
热议问题