Home > front end >  import external CSS file into JavaScript innerHTML
import external CSS file into JavaScript innerHTML

Time:01-31

I have created a webpage using the InnerHtml function in JavaScript. I now want to import some icons into this JavaScript file.

These icons have come from an external site, which contains a CDN link.

How could I do this?

I have tried to write the CDN link inside the tags of the InnerHTML function, as well as in the HTML part of the InnerHTML function. However, neither way imports the icons correctly.

CodePudding user response:

You can use <ion-icon></ion-icon> and specify the name in it like

<ion-icon name="home-outline" ></ion-icon>

Note: It works with ion-icons package only.

Simple example:

* {
  box-sizing: border-box;
}
<html>

<head>
</head>

<body>
  <div >

    <ion-icon name="home-outline" ></ion-icon>

  </div>

  <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js">
  </script>
</body>

</html>

CodePudding user response:

To import icons from an external site into a webpage using InnerHTML in JavaScript, you need to include the icons as elements in the HTML string you pass to the InnerHTML method.

Here's an example using an icon from Font Awesome:

document.getElementById("iconContainer").innerHTML = 
   '<i ></i>';

You will also need to include the Font Awesome CSS in the head of your HTML file:

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" 
      integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" 
      crossorigin="anonymous">

Note that the CSS link should be included in the head of the HTML file, not in the JavaScript file.

  • Related