JavaScript. Include script in document

Home » Tutorials » JavaScript » JavaScript. Include script in document
In upcoming lessons I will answer to your questions and comments which you send me on my youtube channel. In this lesson I’ll consider js scripts including, function calling from one script to another
Scripts work in the order in which they are connected in the document. If you declare function in file script1.js and call it on script2.js, this function will work fine in script2.js. But if you declare function in script2.js and call it in script1.js, function won’t work. Of course you can change script including. But it is unproductively.
To avoid change of order script including, we will create script dynamically, set him source and include to document. But function won’t work again. To get good result, you need “to wrap” calling of this function in onload event (analogue of ready function in jquery).

Code lesson (HTML)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>



    <script src="script1.js"></script>
    <!--<script src="script2.js"></script>-->

    </body>
</html>

Code lesson (script1.js)

var jsFile = document.createElement("script");
jsFile.src = "script2.js";
console.log(jsFile);
document.head.appendChild(jsFile);

function sum(a,b) {
    return a+b;
}

window.onload = function(){
    alert(diff(3,4));
}

Code lesson (script2.js)

function diff(a,b) {
    return a-b;
}

//alert(diff(a,b));

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This