How to add and remove Javascript dynamically

0

I am developing a web application that needs to load modules dynamically, each module has html, css, javascript code fragments, which I upload via ajax with json:

To add the html and the css, the innerHTML method works perfectly for me, which is not the case with Javascript.

here is the code of the petition and answer:

//esta seria la peticion
function requestApplication(e){
    var solicitud = new XMLHttpRequest();
    solicitud.addEventListener('load', requestAplicacionResponse, false);
    var aplicacion = e.target;
    var modulo = aplicacion.parentNode.parentNode;
    var sucursal = modulo.parentNode.parentNode;
    var dataset = sucursal.dataset;
    var url = 'http://' + dataset.host + ':' + dataset.port + '/sistema/aplicacion';
    var paquete = {
        'sesion':sucursal.dataset.sesion,
        'usuario':sucursal.dataset.usuario,
        'perfil': sucursal.dataset.perfil,
        'modulo': modulo.dataset.modulo,
        'aplicacion': aplicacion.dataset.aplicacion
    };
    solicitud.open('POST', url);
    solicitud.send(JSON.stringify(paquete));
}

//este metodo recibe la respuesta del servidor
function requestAplicacionResponse(e){
    var main = document.querySelector('main');//contenedor donde quiero agregar lo solicitado
    //obj es un diccionario clave valor "objeto json" que contiene el codigo que deseo agregar
    var obj = JSON.parse(e.target.responseText);
    main.innerHTML = main.innerHTML + obj.html + obj.css + obj.js;
}

is displayed correctly but has no functionality, apparently it seems that the javascript functions were not added to the javascript interpreter associated with the DOM of the page.

    
asked by Neyer 11.10.2016 в 20:29
source

2 answers

4

It is not possible to add javascript via innerHTML . You must load the script as a separate file or as a label with text. Here is an example of how to do it.

Salu2

Aregar as a label with content:

var script = document.createElement( "script" );
script.type = "text/javascript";
script.text = 'alert("hola mundo")';
document.getElementsByTagName('head')[0].appendChild(script)

Add as file.

You create a label <script> and add it to <head> . The onload event tells you when the script load is complete.

// agregamos archivo-ltr.css o archivo-rtl.css
var script = document.createElement( "script" );
script.type = "text/javascript";
script.src = '/ruta/al/archivo.js';
script.onload = function () {
   // el script se ha cargado 
};

document.getElementsByTagName('head')[0].appendChild(script)

Remove

You search for the <script> tag that you want to delete and delete it. Take into account that this does not imply that the module is completely downloaded, only the source was downloaded, any instance or global variable declared in that module still exists.

var script = document.querySelector('script[src=/ruta/al/archivo.js]')
script.parentNode.removeChild(script);
    
answered by 11.10.2016 / 20:58
source
0

When you add javascript functions at runtime they do not relate to the objects, what you should do is to bind the objects AFTER adding the new functions. Check link

    
answered by 11.10.2016 в 21:24