There is a familiar Ajax (POST) page request. Along with the HTML content of the page, the response script js returns, which is not executed on the client side:

<script> //Здесь много кода </script> 
  • I heard about eval () in js - how safe and correct to use? - Jony
  • And why not return some sign on which the script is executed or not executed? - andreyqin
  • Probably, you did not understand the essence of the question ... - Jony
  • 2
    @Oleg Ponomarchuk, this is a Russian-speaking forum. - zb '
  • one
    So I ask you - is it important to return the js-code from the server? Without this can not do? Run pre-prepared code, for example? - andreyqin

3 answers 3

I don’t know why to do this, but something like this might be suitable for the author:

 var script = document.createElement('script'); script.type='text/javascript'; script.src="script.js"; document.body.appendChild(script); 

There is another option with document.write, but I don’t remember anything.

In general, the question is quite simply searched by the following query: dynamic loading of js scripts.

    Better remove the tags and execute the resulting code with eval (). I do it conveniently. You only need to look so that there are no extra characters, otherwise it will not be executed.

    • Unnecessary tags are <script>? Extra characters are line breaks? - Jony

    From jQuery's documentation for .load ():
    jQuery uses the browser's .innerHTML . During this process, browsers often filter elements from the document such as <html> , <title> , or <head> elements. To load scripts, you should create <script> elements yourself in the document's <head> :

     $('<script>', {src: 'js_file.js'}).appendTo('head');Perhaps you can request a list of scripts to load from the server with ajax: $.post('scripts_to_load.json', function (data) { for (var i = 0; i < data.scripts.length; i++) { $('<script>', {src: data.scripts[i]}).appendTo('head'); } }); 
    • Those. if my response from Ajax returns response.js = "<script> alert ('ok'); </ script>", then the code will be like this: $ ('<script>', {src: response.js) .appendTo ( 'head'); - Jony