Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a javascript file dynamically? [duplicate]

Tags:

javascript

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?

like image 254
user455318 Avatar asked Mar 08 '11 16:03

user455318


People also ask

How do I load a JavaScript script file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I load a JavaScript file asynchronously?

write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously.


2 Answers

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> 
like image 182
Lekensteyn Avatar answered Sep 28 '22 04:09

Lekensteyn


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 
like image 25
JiminyCricket Avatar answered Sep 28 '22 02:09

JiminyCricket