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.

2

2 Answers 2

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')

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.