2013-04-13 11 views
11

Voglio aggiungere script e stili aggiuntivi al mio sito quando viene caricato uno specifico div. Iniziamo definendo un percorso per uno script o un foglio di stile e poi creo un elemento. Di seguito accludo l'elemento al tag head in HTML.aggiungere solo uno script alla testa se non esiste

Ma mi piacerebbe un modo per vedere se lo script o il foglio di stile sono già stati aggiunti prima di aggiungerlo di nuovo. Sarebbe stupido aggiungere uno script o un foglio di stile già esistente.

D: Come utilizzare javascript per verificare se uno script esiste già nel tag head e quindi aggiungere l'elemento se non lo è?

EDIT

Ho fatto una funzione in base alla risposta da @KernelPanik. Non funziona ancora, ma si spera che lo farà. La funzione è attualmente in discussione: my script appending function doesn't work

+3

È possibile inserire un id sul tag script/style/link e verificare se esiste. – Vatev

+0

@Vatev L'unico problema è che è supportato solo da alcuni browser – Dimser

+1

In che modo? document.scripts o document.getElementsByTagName ("script") e i loro attributi sono supportati da tutti i browser – mplungjan

risposta

0

forse headjs può aiutare.

o forse è possibile aggiungere attributo di carico nel tag di script.

il mio inglese è un po 'povero, quindi forse sto fraintendendo la tua domanda.

if(ie){ 
    js.onreadystatechange = function(){ 
    if(js.readyState == 'complete'){ 
     callback(js); 
    } 
} 
else{ 
js.onload = function(){ 
    callback(js); 
} 
+0

Il problema non è quello di aggiungere gli script .. è per rilevare i suoi esistenti e quindi aggiungere script se non esistono già. – Dimser

+0

come js.onload = function() {alert ('loaded');} – Fakefish

3

È possibile utilizzare il DOM getElementsByTagName("script") per ottenere tutti i <script> tag nel documento. Quindi puoi controllare gli url src di ogni tag script restituito, per l'url degli script che hai aggiunto alla sezione head. Allo stesso modo, puoi fare qualcosa di simile per i fogli di stile sostituendo la ricerca di "script" con "stile".

Ad esempio, se l'URL dello script allegata alla sezione <head> è 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 
} 

Analogamente, se l'URL dello stile allegata alla sezione <head> è 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 simile domanda è stata anche posta qui: Check if Javascript script exists on page

10

Se è possibile utilizzare jquery, th è il codice è buono

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); 
} 

Nella tua scrittura di codice

appendScript('/Scripts/myScript.js'); 
appendStyle('/Content/myStyle.css'); 
+0

non è più necessario attribuire "text/javascript" con HTML5 – Serge

+0

Lovely! Cosa succede se dev deve aggiungere jQuery stesso? Vanilla javascript non sarebbe la soluzione ottimale qui? –

-3

Si può provare a chiamare una qualche funzione, file di script oggetto, variabile da quella JS, se lo trova, allora esiste, se non, è necessario inserire il file di script js.

1

Un altro modo con un aiutante funzione come di seguito

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

Esso utilizza Array.prototype.some funzione. Potrebbe essere necessario un es5-shim se siete nei browser che non supportano ES5 (IE7 e IE8 ...)

2
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; 
} 
1

ho usato la soluzione di Jack Lee.È stato facile da implementare e rapidamente versatile con praticamente qualsiasi tipo di file .... Non ho ampliato nulla ... in realtà probabilmente l'ho stordito un po '... volevo solo elencare quello che ho fatto nel caso in cui aiuti qualcuno 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... 
Problemi correlati