Hello!

I have two files main.js and second.js . How to connect the second.js file to the html page correctly and then call the my_function () function located in it ; ?

Connect in this way:

Main.js file

var new_script = document.createElement('script'); new_script.type = 'text/javascript'; new_script.src = 'http://site.ru/second.js'; var head = document.head || document.getElementsByTagName('head')[0]; head.appendChild(new_script); // дальше сразу же вызываю функцию расположенную в файле second.js // выходит следующая ошибка - Предполагается наличие объекта my_function(); 

Second.js file

 function my_function() { alert("HELLO"); } 

    1 answer 1

    Solution found:

     if(new_script.readyState) { new_script.onreadystatechange = function () { if(new_script.readyState == "loaded" || new_script.readyState == "complete") { new_script.onreadystatechange = null; my_function(); } }; } else { new_script.onload = function () { my_function(); }; }