Conditional javascript call in Html5

Asked

Viewed 163 times

1

How can I call a script obeying a conditional on Html5?

For example, depending on the address in the browser it loads a certain script

If the address is http://leituracrista.com/audioplayer/ loads the following script:

<script  src="js/index.js"></script>

If the address is http://leituracrista.com/audioplayer/dispensacao/ loads the following script:

<script  src="dispensacao/js/index.js"></script>

If the address is http://leituracrista.com/audioplayer/hinario/ loads the following script:

<script  src="hinarioCatado/js/index.js"></script>

and so on with several ifs

Thank you!

  • Please avoid long discussions in the comments; your talk was moved to the chat

  • Okay, I’m sorry, the discussion really got long.

2 answers

3

Try:

const URL1 = "http://leituracrista.com/audioplayer/";
const URL2 = "http://leituracrista.com/audioplayer/dispensacao/";
const URL3 = "http://leituracrista.com/audioplayer/hinario/";

let url = window.location.href;

if ( url === URL1) {
    include("js/index.js");
}else if ( url === URL2) {
    include("dispensacao/js/index.js");
}else if (url === URL3 ) {
    include("hinarioCatado/js/index.js");
}

function include(file) {

    let script  = document.createElement('script');
    script.src  = file;
    script.type = 'text/javascript';
    script.defer = true;

    document.getElementsByTagName('head').item(0).appendChild(script);
}    
  • As soon as I get home I’ll take a test.

  • It worked perfectly @Bruno Morales

  • I’m glad I could help!

1


Since you don’t want to use multiple index files, the solution involves using parameters in the url.

Examples index.htm?id=audioplayer index.htm?id=dispensacao index.htm?id=hinario

//location.search retorna a parte querystring de um URL, incluindo o ponto de interrogação (?)
//.split divide o url em duas partes, uma antes do ? e outra depois do ?

var variaveis=location.search.split("?");

//variaveis[1] é a parte depois do ? que será quebrada em duas partes, uma antes de = e outra depois de =

var quebra = variaveis[1].split("=");

//quebra[1] é a segunda parte, depois de = que corresponde ao valor do parametro passado na url
//de posse desse valor é só fazer a verificação e chamar o js correspondente

if (quebra[1]=="audioplayer"){
    document.write('<script type="text/javascript" src="index.js"><\/script>');
} else if (quebra[1]=="dispensacao") {
    document.write('<script type="text/javascript" src="dispensacao.js"><\/script>');
} else if (quebra[1]=="hinario") {
    document.write('<script type="text/javascript" src="hinario.js"><\/script>');
}else{
    document.write('<script type="text/javascript" src="index.js"><\/script>');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.