How to load correctly Jquery and Bootstrap

1

Good morning everyone, I'm making a website that uses JQuery and Bootstrap (including some plugins like DateTimePicker). More or less I get it to work but I can not make it clear to me the subject of the loads of the different scripts and styles. For example, I have the following home page, a form that validates if a user exists:

<html>
<head>
  <title></title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src='js_propio/cookies.js'></script>
  <script src='js_propio/funciones.js'></script>
  <script src='js_propio/eventos.js'></script>


  <!-- -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" type="text/css" href="assets/css/vendor.css">
  <link rel="stylesheet" type="text/css" href="assets/css/flat-admin.css">

  <!-- Theme -->
  <link rel="stylesheet" type="text/css" href="assets/css/theme/blue-sky.css">
  <link rel="stylesheet" type="text/css" href="assets/css/theme/blue.css">
  <link rel="stylesheet" type="text/css" href="assets/css/theme/red.css">
  <link rel="stylesheet" type="text/css" href="assets/css/theme/yellow.css">  
</head>
<body>

<!-- AQUI VA EL CONTENIDO -->

  <script type="text/javascript" src="assets/js/vendor.js"></script>
  <script type="text/javascript" src="assets/js/app.js"></script>
  <script src='js_propio/cookies.js'></script>

</body>
</html>

For the functions that I have programmed, I carry out the loads of the other pages with a GET method, which cleans a certain DIV and loads inside the html.

Here is an example of the function:

 $('body').on('click', "#btnCita", function(ev){
      $.get( "form.html", function( data ) {
           $("#carga").html('');
           $("#carga").html(data);
           selecEspecialidad();
    });           
  });

The problem that arises is that, if I leave the calls to scripts that are in your head (the same as those in the head of the main page) many times the functions are executed twice, instead, if I delete them and leave html only, trying to make use of the scripts that are on the main page, they do not run.

Likewise, in another of the charges, I call a page with a form, in which one of the fields is a calendar (in Spanish).

  

The problem here lies in that, the calendar configuration is   found within a $ (document) .ready (function ()), so it does not   it executes correctly when executed when loading the page, and not at   be loaded on the main page (I do not know if I explained myself well)

(EDITION: this last paragraph I can not edit it to improve the writing because the idea is not understood).

     <div class="row" id="datosCita">
        <div class="col-md-12">
          <div class="card">
            <div class="card-header oculto">
              Rellene los siguientes datos
            </div>
            <div class="card-body">
              <div class="row"> 
                <div  id="datos" class="oculto">
                  <select class="select2" id="listEspec">
                    <option value="0">-- Seleccione una especialidad --</option>
                  </select>
                </div>
                <div id="profesionales" class="oculto">
                  <select class="select2" id="listProf">
                    <option value="0">-- Seleccione un profesional --</option>
                  </select>
                </div>
                <div class="input-group oculto">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY" type="text"/>
                </div>
              </div>
              <div id="cargaTablaCitas"></div>     
              <div id="iconosNav">
                <img src="iconos/siguiente.png" id="btnSiguiente" style="cursor: pointer;"/>
              </div>
            </div>
          </div>
            </div>
          </div>
        </div>
        <div class="col-md-12">
          <div class="form-footer">
            <div class="form-group">
              <div class="col-md-9 col-md-offset-3">
                <button type="submit" class="btn btn-primary">Confirmar cita</button>
                <button type="button" class="btn btn-default">Cancelar</button>
              </div>
            </div>
          </div>
        </form>
            </div>
          </div>
        </div>
      </div>
    </div>

      </div>

      <script type="text/javascript" src="assets/js/vendor.js"></script>
      <script type="text/javascript" src="assets/js/app.js"></script>
       <script src='js_propio/cookies.js'></script>

    <!-- Include Date Range Picker -->

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<script src="js/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/locales/bootstrap-datepicker.es.min.js"></script> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<script type="text/javascript">
      $(document).ready(function(){

        var date_input=$('input[name="date"]'); //our date input has the name "date"
        var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
        date_input.datepicker({
        useCurrent: false,
        format: 'dd/mm/yyyy',
        container: container,
        todayHighlight: true,
        autoclose: true,
        startDate: "today",
        language: 'es'
        }).on('closeUp',function(){
          var marca = true;
          if(marca == true){
             alert($(this).val());

          }
          //alert('a');

        })
      })
    </script>

    <script src='js_propio/eventos.js'></script>

As I said before, I can make it work but changing the order of the script in a crazy way.

    
asked by AntonioMP87 10.05.2017 в 10:29
source

3 answers

2

the order is explained by Minerillo very well, I opted for the following although it does not have much validity in my work (afterwards I explain why):

CSS Style Sheets

in <head>

<head> <link href="css/bootstrap.css" rel="stylesheet"> <link href="css/cssOtrasLibrerias.css" rel="stylesheet"> <link href="css/cssCreadorPorMi.css" rel="stylesheet"> </head>

Remember that CSS is overwritten and always takes the last one, if it is an identical definition, that's why you always start with the Framework , then the librerias (such as alerts, manners, themes, etc. ..) and finally the custom ones.

JS Methods and Scripts

before closing the <body>

   <script src="js/jquery.js"></script>
   <script src="js/bootstrap.js"></script>
   <script src="js/pluginX.js"></script>
   <script src="js/libreriaY.js"></script>
   <script src="js/misMetodos.js"></script>
   <script>console.log('otros metodos');</script>
</body>

The order here does influence, since bootstrap needs jquery , so it needs to be loaded, and maybe one plugin needs another like the datepicker and the datetimepicker that are dependent.

Everything in order and very well arranged.

Common Questions:

Why do I run the function twice?

Because if you load a file with .load (), reload a page with all its scripts, it is normal to run 2 or more times.

How can I load content from another page without this happening?

Well, you have already loaded the CSS and the JS, so in theory your pages that you are going to load should only have the HTML, because if you are not duplicating code.

But if I only load the HTML, why does not my JS work?

As he said @Minerillo, it's a problem of wanting to assign something, to something else that does not exist yet. and for that the following:

Suppose you have a HTML code, so

<div class="contenido">
   <button id="llamar">Llamar Algo</button>
</div>

and that on the first page you have a JS method (or function);

$(document).ready(function(){
   $('#llamar').on('click', function(){ alert('llamando')});
});

Since the document is ready when you click on the button it executes the call, everything cool up here.

Now you have another HTML (boton.html)

<button id="nada">Alertar Nada</button>

you load it with .load() to the div that we mentioned before

$(document).ready(function(){
   $('#llamar').on('click', function(){
       $('.contenido').load('boton.html');
   });
});

And you want that new button now to do something and put it there too:

$(document).ready(function(){
   $('#llamar').on('click', function(){
       $('.contenido').load('boton.html')
   });

  $('#nada').on('click', function(){
       alert('Presionaste Nada');
  });
});

but ... it does not work: (

Why does not the new button work?

You see, the content is loaded the first time, that activates the $(document).ready()' cuando tu cargas otro HTML que no existia en el momento que $ (document) .ready () 'happened, because there is no way to say that it reacts to your event .on('click') , that's why it does not do anything.

How would your mother send you tortillas if you are not born yet? (An example in real life)

How to solve it?

You'll see. suppose that you can not order something from something that does not exist, however you know where and when it will exist.

Well the long explanation here: link

To assign an event to something that we know will exist, we must add it to the person who contains it, in this case our <div class="contenido">

Then:

<!--                           |-- Este hace la magia               -->
<!--                           |                                   -->
$('.contenido').on('click', '#nada', function(){
    alert('Presionaste Nada');
});

Functional because you are assigning an event to something that already exists. And this in turn will know which element activates the event.

Our final code looks like this:

$(document).ready(function(){
   $('#llamar').on('click', function(){
       $('.contenido').load('boton.html')
   });

  $('.contenido').on('click', '#nada', function(){
       alert('Presionaste Nada');
  });
});

Why did you say that the order form is no longer used?

Today precompilers, transpilers and packers are fashionable. Which gather all the code, crush it and compress it leaving a site that consists of 2 files.

Decreasing requests, although sacrificing other things. Then in the end that series of tools accommodate everything. Although of course it is not magic and you must have mastered these topics to know what you are doing.

Greetings.

    
answered by 11.05.2017 в 15:31
1

The main reason why Bootstrap fails is when it does not have Jquery previously.

In the Bootstrap documentation they comment on the need for JQuery, this BEFORE Bootstrap JS.

* First of all <script type="text/javascript" src="assets/js/jquery-X.X.X.min.js"></script> You can find the latest jquery version at:
link
* And then the bootstrap
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>

And then the rest of the libraries that you need and want, but I recommend putting these two first in the JS script.

    
answered by 11.05.2017 в 14:53
0

Good morning.

Dependencies in Javascript ES5 are satisfied in cascade, so that first the HTML file includes those javascript files that do not depend on any other file, and finally, the one that needs the previous ones is added.

In your case, as we are using Bootstrap 3 it would be:

<script type="text/javascript" src="pathTojQuery.min.js"></script>

and then

<script type="text/javascript" src="pathToBootstrap.min.js"></script>

In this way, when the bootstrap.min.js file searches for the jQuery dependency needed for it, it is already loaded because it was previously declared and consequently, it will be loaded before bootstrap.

In the case of Boostrap 4, which is still in the alpha version, you would first have to load jQuery, then tether (another dependency of bootstrap 4), and finally bootstrap. That way we avoid that the console of errors of the navigator shrieks us with the annoying errors.

Greetings

    
answered by 11.05.2017 в 15:11