[英]Rendering HTML from external javascript
I have a task to show my product list on my client's websites.我的任务是在客户的网站上显示我的产品列表。 My idea is include my JavaScript file in client's websites call a function like this,
我的想法是在客户的网站中包含我的 JavaScript 文件,这样调用 function,
<div id="my-product-list"></div>
<script src="https://example.com/myscript.js"></script>
const myproducts = new Products('#my-product-list', 12323);
myproducts .setup();
</script>
Is this the right way to achieve this?这是实现这一目标的正确方法吗?
If yes, How can I include css styles( media
queries) for my elements?如果是,我如何为我的元素包含 css 样式(
media
查询)?
If no, what is the best way to do this?如果不是,最好的方法是什么?
Yes.是的。 That is certainly a way to achieve what you need.
这当然是实现您所需要的一种方式。
To include styles you can simply make a link to your styles in the same way you reference your script.要包含 styles,您只需以与引用脚本相同的方式链接到 styles。
Clients Website客户网站
<div id="my-product-list"></div>
<script src="https://example.com/myscript.js"></script>
<script>
initProducts('#my-product-list', '31337')
</script>
<link href="https://example.com/mystyles.css" rel="stylesheet">
myscript.js myscript.js
function initProducts(selector, clientId) {
const baseEl = document.querySelector(selector)
if (baseEl) {
fetch('http://example.com/products/' + clientId)
.then(response => response.json())
.then(data => {
baseEl.innerHTML = data
});
} else {
console.warn('baseEl not found', selector)
}
}
mystyles.css mystyles.css
#my-product-list {
...
}
#my-product-list div {
...
}
@media (min-width: 600px) {
#my-product-list {
...
}
}
Doing what you're suggesting is a viable solution, however the way you have it wouldn't work as you're ending a script tag, and not starting it for your function call.执行您的建议是一个可行的解决方案,但是您拥有它的方式将无法工作,因为您要结束脚本标签,而不是为您的 function 调用启动它。
It should be like this:它应该是这样的:
<div id="my-product-list"></div>
<script src="https://example.com/myscript.js"></script>
<script>
const myproducts = new Products('#my-product-list', 12323);
myproducts.setup();
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.