Saturday 3 June 2017

Pure javascript equivalent for including one js file into another

I have three files index.html,1.js,2.js. I want to include the js file into another js file dynamically and I know that I can do it using ajax call or using $.getScript() of jQuery or by using node.js

But I want to do it using pure javascript. I want to include 2.js in 1.js and use the functions of it in 1.js somehow!

<html>
<head>
    <script type="text/javascript" src="1.js"></script>
<!--<script type="text/javascript" src="2.js"></script>-->

</head>
<form action="" >
    <button  id="button1">Click
    </button>
</form>

</html>

1.js

document.addEventListener('DOMContentLoaded',function(e){
    e.preventDefault();
     var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= '2.js';
   head.appendChild(script);

})

2.js

document.getElementById("button1").addEventListener("click",function(e){
    e.preventDefault();
function myFunction(){
        alert("hello");
    }
});



via aayushi

No comments:

Post a Comment