最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Load and Execute Styles and Scripts from an External HTML into a Web Component (Shadow DOM)? - Stack Overflo

programmeradmin0浏览0评论

I am currently using an iframe to load a Next.js application into my JavaScript application using its domain. However, I would like to migrate from using an iframe to rendering the Next.js application within a Shadow DOM. Unfortunately, I am facing issues rendering the Next.js application inside the Shadow DOM.

I’m trying to fetch the domain’s content and load it into the Shadow DOM, like this:

function loadNextJsContent(shadowRoot) {
  return new Promise((resolve, reject) => {
    // Fetch the HTML content from the Next.js app hosted at 
    fetch('http://localhost:3333/page-1-uifndi')
      .then(response => {
        if (!response.ok) {
          reject(new Error('Failed to fetch Next.js content'));
        } else {
          return response.text();
        }
      })
      .then(htmlContent => {
        const headContent = htmlContent.match(/<head[^>]*>([\s\S]*?)<\/head>/i)[1];
        console.log('HTML Content:', htmlContent, headContent);

        const template = document.createElement('template');
        template.innerHTML = htmlContent;
        
        shadowRoot.appendChild(template.content.cloneNode(true));
        resolve();
      })
      .catch(error => {
        // Handle errors and inject failure message into the Shadow DOM
        console.error('Error loading Next.js content:', error);
        shadowRoot.innerHTML = '<p>Failed to load content.</p>';
        reject(error);
      });
  });
}

loadNextJsContent(shadowRoot)
.then(() => {
  console.log('Next.js content loaded successfully!');
})
.catch(error => {
  console.error('Failed to load content:', error);
});

HTML Elements in inspect

I am currently able to retrieve only the HTML content, but I am unable to load the associated CSS, scripts, and fonts. Even though the content is loaded into the Shadow DOM, the styles and scripts do not appear in the network tab or take effect. What I am aiming for is functionality similar to an iframe, which automatically loads all the CSS and scripts when provided with a URL. Since Shadow DOM doesn’t support direct URL rendering, is there a way to load the complete domain content and render it within the Shadow DOM?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论