They said to make ajax , which will load the js script in the tag, not the .js file itself, but the script inserted in the page, and so that the Java script would then work. How can I do that? And the library can not be used.

    2 answers 2

    If I understood correctly, then it is necessary to execute pure js code on the client. Then the task consists of two subtasks:

    1. Download script from server
    2. Execute script

    Download script.

    We use xmlhttprequest

     // Кросбраузерный вариант создания запроса function getXmlHttp(){ var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } // теперь сам запрос var xmlhttp = getXmlHttp()'GET', '/xhr/test.js', true); // где /xhr/test.js - адрес скрипта xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { if(xmlhttp.status == 200) { eval( '(' + xmlhttp.responseText + ')'); } } }; xmlhttp.send(null); 

    Script execution

    Pay attention to the line

     eval( '(' + xmlhttp.responseText + ')'); 

    eval - executing script method, more details here.

    • 2
      eval is evil, it's better to simply attach the script to the body and it will execute - markuper
    • I agree. But it was too lazy to write her insert without jquer - Dmitry Manannikov

    Variant without eval, we just create a tag when loading, which will be executed

     var scriptEl = document.createElement('script'); scriptEl.src = url // url = то ссылка на скрипт document.body.appendChild(scriptEl); 

    It is better to place body at the beginning (not in the head , since then the body will not) If you place it in the head , then instead of document.body , you will need to write document.head

    • And nothing that the issue is 3 years old, Mr. archeologist? - user31688