Is it possible to create a JS file for all pages?

Asked

Viewed 307 times

0

I have several pages, I wonder if it is possible to use the same JS on the same page.

For example:

I have a HOME page, where I carry the pages "son" inside a div (content), but for each page, I need to create a new file JS.

$("#lista_cli").click(function(){
    $('#content').css('display', 'none');
    $("#content").load('lista_clientes.php');
    $("#content").fadeIn(2000);
});

$("#cadastro_cli").click(function(){
    $('#content').css('display', 'none');
    $("#content").load('cadastra_cliente.php');
    $("#content").fadeIn(2000); 
});

I’ve been doing some tests, at some point, when I give a ALERT in the archive JS of the home page, in one content of the other page (after loaded), it displays me a alert correctly, however the requests AJAX don’t work. Maybe I got a little confused, but basically:

It is possible to use the same JS on several pages? is recommended?

1 answer

0


If the code in the JS file is common to more than one page, you can certainly reuse it, not only can it but it should, after all this is one of the main advantages of separating javascript code into a separate html file.

To use the same file on more than one page, simply import it into your html pages, e.g..:

<script src="meuScript.js"></script>
  • Just to complement, code reuse is a good practice, as Arnaldo has already said, not only to avoid unnecessary duplication of code, but to facilitate maintenance. Imagine that you have a generic Alert that you use on all screens and you need to change all the texts from that Alert. Instead of going page by page to tidy up each Alert code, you, having shared (reused) it on other pages, can change the code only 1x and have a "global effect".

Browser other questions tagged

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