简体   繁体   中英

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,

    <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?

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.

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

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

#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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM