javascript - onLoad does not work when replacing <script> with html-react-parser - Stack Overflow

I am using the html-react-parser library to convert a string representing an HTML snippet into a React

I am using the html-react-parser library to convert a string representing an HTML snippet into a React component. The string contains a component and a with an onload attribute. Here’s an example of the HTML string:

const html = `
  <div id="component">...</div>
  <script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;

The HTML string is processed and converted into a React component using html-react-parser. The approach involves parsing the string and replacing local sources with sources hosted on a CDN. To achieve this, I use the replace option from html-react-parser. Here is my current implementation:

import parse from 'html-react-parser';

const html = `
  <div id="component">...</div>
  <script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;

const parsedHTML = parse(html, {
  replace(domNode) {
    if (isAReplaceableScript(domNode, 'true')) {
      return replaceLocalScript(domNode, customization.javascript);
    }
  },
});
const replaceLocalScript = (domNode, files) => {
  const localSource = domNode.attribs.src;
  const cdnSource = files[localSource];
  const { attribs } = domNode;
  const onLoad = new Function('alert("It is working")');
  const updatedAttribs = { ...attribs, src: cdnSource };
  return cdnSource ? <script {...updatedAttribs} onLoad={onLoad} defer /> : <></>;
};

The updated appears correctly in the browser’s HTML with the src attribute pointing to the CDN URL, but the onLoad event does not trigger. When inspecting the script in the browser, the onLoad property does not appear.

Questions

  1. What might be missing for the onLoad event to trigger?
  2. Is it possible that React or html-react-parser is ignoring the onLoad event for <script> tags?
  3. Should I use a different approach to dynamically load scripts?

Additional Context

  • Due to technical limitations, this approach is the most cost-effective to implement.
  • The HTML string is processed to be converted into a React component, as this project is built with React.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742387807a4434410.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信