0

I am working on one requirement where I need to load a script and stylesheet inside javascript file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

How can I load these into my javascript file.

Ashutosh Rai
  • 123
  • 9
  • Does this answer your question? [Inserting script and link tag inside the header tag](https://stackoverflow.com/questions/19673398/inserting-script-and-link-tag-inside-the-header-tag) – segFault Jul 09 '20 at 11:28
  • Does this answer your question? [How to load up CSS files using Javascript?](https://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript) – Ahmed Tag Amer Jul 09 '20 at 11:31

2 Answers2

2

You could easily create functions to add the script/link elements to the document's head.

const documentHead = () => {
  return document.getElementsByTagName('head').item(0) ||
      document.documentElement
}

const loadJavaScript = (src) => {
  let script = document.createElement('script')
  script.setAttribute('src', src)
  documentHead().appendChild(script)
} 

const loadCSS = (href) => {
  let stylesheet = document.createElement('link')
  stylesheet.setAttribute('rel', 'stylesheet')
  stylesheet.setAttribute('href', href)
  documentHead().appendChild(stylesheet)
} 

const loadExternal = (path) => {
  let [filename] = path.split(/[\\\/]/g).slice(-1)
  let [extension] = filename.split(/\./g).slice(-1)
  switch (extension) {
    case 'js'  : loadJavaScript(path) ; break
    case 'css' : loadCSS(path)        ; break
  }
} 

loadExternal('https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js')
loadExternal('https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css')
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

I would recommend you use jQuery as it is much easier to use than plain JavaScript.


But if you want to add css codes in a javascript file, you can try:

$("#id").css("param","prop");

Example:

$("#id").css("color","red");

About linking to an external CSS file? Try @Mr. Polywhirl's solution.

Hope it helps..