18

I want to add additional scripts and styles to my site when a specific div is loaded. I start out by defining a path to either a script or stylesheet and then create an element. Hereafter I append the element to the head tag in HTML.

But I would like a way to see if the script or stylesheet already has been append before I append it again. It would be stupid to append an already existing script or stylesheet.

Q: How do I use javascript to check wether or not a script already exists in the head tag, and then append the element if not?

EDIT

I have made a function based on the answer from @KernelPanik. It doesn't work yet but hopefully it will. The function is currently in question: my script appending function doesn't work

Community
  • 1
  • 1
Corfitz.
  • 1,864
  • 3
  • 31
  • 53

7 Answers7

15

If you can use jquery, this code is good

function appendScript(filepath) {
    if ($('head script[src="' + filepath + '"]').length > 0)
        return;

    var ele = document.createElement('script');
    ele.setAttribute("type", "text/javascript");
    ele.setAttribute("src", filepath);
    $('head').append(ele);
}

function appendStyle(filepath) {
    if ($('head link[href="' + filepath + '"]').length > 0)
        return;

    var ele = document.createElement('link');
    ele.setAttribute("type", "text/css");
    ele.setAttribute("rel", "Stylesheet");
    ele.setAttribute("href", filepath);
    $('head').append(ele);
}

In your code write

appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');
9
var lib = '/public/js/lib.js';

if (!isLoadedScript(lib)) {
  loadScript(lib);
}

// Detect if library loaded
function isLoadedScript(lib) {
  return document.querySelectorAll('[src="' + lib + '"]').length > 0
}

// Load library
function loadScript(lib) {
  var script = document.createElement('script');
  script.setAttribute('src', lib);
  document.getElementsByTagName('head')[0].appendChild(script);
  return script;
}
Jack Lee
  • 929
  • 7
  • 5
4

You can use the DOM getElementsByTagName("script") to get all of the <script> tags in the document. Then you can check the src urls of each script tag returned, for the url of the script(s) that you have added to the head section. Likewise, you can do something similar for the style sheets by replacing the search of "script" with "style".

For example, if the url of the script appended to the <head> section is header_url.html

var x = document.getElementsByTagName("script");
var header_already_added = false;

for (var i=0; i< x.length; i++){
    if (x[i].src == "header_url.html"){
        // ... do not add header again
        header_already_added = true;
    }
}

if (header_already_added == false){
    // add header if not already added
}

Likewise, if the url of the style appended to the <head> section is header_style.css

var x = document.getElementsByTagName("style");
var header_already_added = false;

for (var i=0; i< x.length; i++){
    if (x[i].src == "header_style.css"){
        // ... do not add header again
        header_already_added = true;
    }
}

if (header_already_added == false){
    // add header if not already added
}

A similar question was also asked here: Check if Javascript script exists on page

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
KernelPanik
  • 8,169
  • 1
  • 16
  • 14
  • I like this answer but failed to use it with Chrome, as Chrome prepends `"http://localhost/"` in case that a relative path was used, e.g. `test.js`. I now use `x[i].getAttribute('src')` – HHFox Nov 23 '20 at 11:55
2

I used Jack Lee's solution. It was easy to implement and quickly versitile with just about any type file.... I didn't expand on anything ...I actually probably stupefied it a bit... just wanted to list what I did in case it helps someone else...

var lib_jq = '//pathtofile/jquery.js';
var lib_bs = '//pathtofile/bootstrap.min.3.5.js';
var lib_cs = '//pathtofile.css';

 ///checks files with the SRC attribute
function isLoadedScript(lib) {
    return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
///checks files with the HREF attribute
function isLoadedCss(lib) {
    return document.querySelectorAll('[href="' + lib + '"]').length > 0
}
///loads the script.js files
function loadScript(link) {
   document.write('<scr' + 'ipt type="text/javascript" src="'+link+'"></scr' + 'ipt>');
}

///loads the style.css files
function loadCss(link) {
   document.write('<link rel="stylesheet" href="'+link+'">');
}

 /// run funtion; if no file is listed, then it runs the function to grab the URL listed. ///Run a seperate one for each file you wish to check. 
if (!isLoadedScript(lib_jq)) { loadScript(lib_jq); }
if (!isLoadedScript(lib_bs)) { loadScript(lib_bs); }
if (!isLoadedCss(lib_cs))    { loadCss(lib_cs);    }

I know there is always a "better" and more "elegant" solution, but for us beginiers, we got to get it working before we can start to understand it... 
1

Another way with a function helper like below

function isScriptAlreadyPresent(url) {
  var scripts = Array.prototype.slice.call(document.scripts);
  return scripts.some(function(el) {
     return el.src && el.src != undefined && el.src == url;
  });
}

isScriptAlreadyPresent('http://your_script_url.tld/your_lib.js');

It uses Array.prototype.some function. You may need a es5-shim if your are in browsers not supporting ES5 (IE7 and IE8...)

Thomas Gratier
  • 2,311
  • 1
  • 14
  • 15
0

maybe headjs can help you.

or maybe you can add onload attribute in the script tag.

my english is a little poor,so maybe i'm misunderstand your question.

if(ie){
  js.onreadystatechange = function(){
    if(js.readyState == 'complete'){
      callback(js);
  }
}
else{  
js.onload = function(){
  callback(js);
}
Fakefish
  • 315
  • 1
  • 2
  • 9
-3

You can try calling some function, object, variable from that js script file, if it finds it then it exists, if not, you need to insert that js script file.

BobG8
  • 1