html - Alert or Console.log not working from dynamically loaded JavaScript -


i use following function dynamically load javascript:

function loadjs(file, c) {     var jsel = document.createelement("script");     jsel.type = "application/javascript";     jsel.src = file;     jsel.async = false;     document.body.appendchild(jsel);     if (c) { jsel.addeventlistener('load', function (e) { c(null, e); }, false); }     document.getelementsbytagname("head")[0].appendchild(jsel); } 

below 1 of functions contained within dynamically added file:

function formelements_select_add(x) {     console.log("add");     alert("add");     var id = x[1];     var value = x[2];     var index = x[3];     var select = document.getelementbyid(id);     var option;     option = document.createelement("option");     option.text = value;     select.add(option, index); } 

i know javascript file gets added correctly , function gets executed because option added select element. why alert , console.log not execute? if click inspect, there no error messages.

edit

this code use call function:

var typeandelement = x[0][0] + "_" + x[0][1]; start = + 1; if (!window[typeandelement]) {     loadjs("https://websemantica.org/scripts/" + x[0][0] + "/" + x[0][1] + ".js", continuemanipulatingelements(typeandelement, actions, x, start, total));     return; } else {     fn = window[typeandelement + "_" + x[0][2]];     if (typeof fn === 'function')         fn(x); } 

i didn't want include initially, because knew working , unclear how works considering using dynamic data.

also, have edited loadjs function:

function loadjs(file, c) {     var jsel = document.createelement("script");     jsel.type = "text/javascript";     jsel.src = file;     jsel.async = false;     if (c) { jsel.addeventlistener('load', function (e) { c(null, e); }, false); }     document.getelementsbytagname("head")[0].appendchild(jsel); } 

the problem appears solved now.

three things jump out:

  1. you're appending script page twice, once document.body, , other document.getelementsbytagname("head")[0]. second 1 move script first place second. need 1 of those.

  2. you're looking load event after appending element. if script in cache, can miss event. hook before appending script dom.

  3. you're not doing in quoted code call function that's defined script you're adding.


other side notes:

  • no need set type, default javascript.
  • no need set async, dynamically-inserted script elements async (now, wasn't true).
  • as jarosław wlazło points out document.alert isn't function; alert need. :-)

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -