Ashutosh Rai
Ashutosh Rai

Reputation: 125

Loading script into javascript

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.

Upvotes: 0

Views: 77

Answers (2)

Master Of Disaster
Master Of Disaster

Reputation: 387

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

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

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

Upvotes: 2

Related Questions