Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding script/css to DOM using Javascript

Tibco is removing JQuery from Spotfire and I have some Dashboards relying on Jquery to work, as shown bellow:

var css = "https://localhost/css/style.css";

if (!$('link[href="' + css +'"]').length) {
    $("<link/>", { "rel": "stylesheet", "type": "text/css", "href": css }).appendTo("head");
}

I would like to do the same using Javascript, but I was unable to find a solution that allow me to load the CSS only if does not exist in DOM.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const cssHref = "https://localhost/css/style.css";

// If element not found returns `null`
const stylesheet = document.querySelector(`link[href="${cssHref}"]`)
if (!stylesheet) {
  // You can create your own helper function to simplify the creation of the element
  // instead of manually creating the <link> element
  const style = document.createElement('link')
  style.rel = 'stylesheet'
  style.href = cssHref

  document.head.append(style)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading