0

i created a library with vanilla js and css, but it just work when i import the js and css, i want to use just importing the file js

right now i am importing this way:

<head>
    <script src="../lib.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>

but its possible only with this?

<head>
    <script src="../lib.js"></script>
</head>

1 Answers1

0

If you wish to do this by hand, you would add code to ../lib.js to have it inject the stylesheet via a link tag when it itself is loaded.

Here's a basic implementation:

// ../lib.js
"use strict";

(function () {
  function injectCSS(href) {
    const link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css"; 
    link.href = href;

    document.head.appendChild(link);
  }

  injectCSS("styles.css");
}());

// rest of ..lib.js as it is currently
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84