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
- What might be missing for the
onLoad
event to trigger? - Is it possible that React or
html-react-parser
is ignoring theonLoad
event for<script>
tags? - 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条)