31

I have this code:

    <script type="text/javascript">
    function js() {
        var getJs = document.getElementById("jogo");

        if (JS == true) { //if button JS is pressed - it is correct?

            < script type = "text/javascript"
            src = "file1.js" >


        } else < script type = "text/javascript"
        src = "file2.js" >
</script>
}
</script>

it doesn't work. I gave two buttons, if the first is pressed, file1.js should be loaded. In case the second one is pressed, file2.js should be loaded.

How can I do that?

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
user455318
  • 3,280
  • 12
  • 41
  • 66
  • what you mean with eval? thanks – user455318 Mar 08 '11 at 16:35
  • `if (JS == true)` dosent mean it being pressed, it simply mean that element is exist in the DOM and why dont u just include all the script and then call the appropriate function based on the existence of the JS – slier Mar 08 '11 at 16:36
  • 2
    @user455318: eval is used to execute a string as Javascript code @kjy112: no you do not. Please do not suggest `eval` as solution unless it's the only way to do. Bad guides would suggest code like `eval("document."+id+".value="+numericValue)`. That is highly insecure! – Lekensteyn Mar 08 '11 at 16:38

5 Answers5

74

You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:

<script type="application/javascript">
function loadJS(file) {
    // DOM: Create the script element
    var jsElm = document.createElement("script");
    // set the type attribute
    jsElm.type = "application/javascript";
    // make the script element load file
    jsElm.src = file;
    // finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
}
</script>
<button onclick="loadJS('file1.js');">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
  • 6
    Please add note that functions from loaded javascript file are not available right after calling "document.body.appendChild(jsElm);", but there is jsElem.onload event that signals when js is ready. – pera Oct 12 '15 at 10:41
  • What about using `document.write(unescape("%3Cscript src='file.js' type='text/javascript'%3E%3C/script%3E"));` – Ithar Feb 24 '16 at 09:27
  • 1
    @Ithar `document.write` should be avoided, see https://developer.mozilla.org/en-US/docs/Web/HTML/Optimizing_your_pages_for_speculative_parsing – Lekensteyn Feb 25 '16 at 09:21
  • Hi, @Lekensteyn I was working with the same dynamic javascript loading. I have used the above-mentioned code but still, my page gets stuck for 2-3 seconds and then my loader is displayed. Any advice on why it is happening. Tried async attribute as well. – Deepankshee Jain Apr 16 '20 at 11:10
  • @DeepanksheeJain if you have a large file, it may take a while before the download is completed. – Lekensteyn Apr 18 '20 at 11:33
13

Try this on for size: Dynamically Load JS

function loadjscssfile(filename){
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js") //dynamically load and add this .js file
JiminyCricket
  • 7,050
  • 7
  • 42
  • 59
  • 1
    You don't use the 'filename' paramater in this function, so it wouldn't work..... 5 years late comment:-) Good link though – Drenai Mar 29 '17 at 08:25
6

JavaScript:

function loadScript(url)
{
    document.body.appendChild(document.createElement("script")).src = url;
}
function loadDefaultScript()
{
    loadScript("http://mysite.com/file1.js");
}
function loadAlternateScript()
{
    loadScript("http://mysite.com/file2.js");
}

HTML:

<input type="button" onclick="loadAlternateScript()" value="Alternate" />
<input type="button" onclick="loadDefaultScript()" value="Default" />
gilly3
  • 87,962
  • 25
  • 144
  • 176
0

You can use this function this will work perfectly

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
Bhushan Pawar
  • 451
  • 4
  • 13
  • you can take a look at the link: [answer](https://stackoverflow.com/questions/40808425/how-load-and-use-dynamically-javascript/45489130#45489130) – asmmahmud Aug 03 '17 at 15:58
0

Via Jquery:

 var getJSfile = function(src) {
            var jsfile = $("<script type='text/javascript' src='"+src+"'>");
            $("head").append(jsfile); 
        }; 

    getJSfile ("home.js");
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
  • you can take a look at the link: [answer](https://stackoverflow.com/questions/40808425/how-load-and-use-dynamically-javascript/45489130#45489130) – asmmahmud Aug 03 '17 at 15:58