Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically load and use/call a JavaScript file?

Tags:

javascript

I need to dynamically load a JavaScript file and then access its content.

File test.js

test = function () {
    var pub = {}
    pub.defult_id = 1;
    return pub;
}()


In this case it works:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="/test.js"></script>    
</head>
<body>
    <script type="text/javascript">
        console.log(test.defult_id);
    </script>
</body>
</html>


But I need to load it dynamically, and that way it does not work:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function loadjs(file) {
            var script = document.createElement("script");
            script.type = "application/javascript";
            script.src = file;
            document.body.appendChild(script);
        }
        loadjs('test.js');
        console.log(test.defult_id);
    </script>
</body>
</html>


Error: Uncaught ReferenceError: test is not defined(…)

like image 498
Alexandre Neukirchen Avatar asked Nov 25 '16 15:11

Alexandre Neukirchen


People also ask

How do I load a JavaScript script?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.

What is the fastest way to load JavaScript?

Optimize Javascript Placement Place your javascript at the end of your HTML file if possible. Notice how Google analytics and other stat tracking software wants to be right before the closing </body> tag. This allows the majority of page content (like images, tables, text) to be loaded and rendered first.


1 Answers

You could do it like this:

function loadjs(file) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = file;
    script.onload = function(){
        alert("Script is ready!"); 
        console.log(test.defult_id);
    };
    document.body.appendChild(script);
 }

For more information read this article : https://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

like image 182
eztam Avatar answered Oct 11 '22 13:10

eztam