1

Hi
I want to write a condition in JS that will result in adding an external js.
For example if the condition is x > 2 and it is true then i want it to load a different external js file but if its false then load another js file.
How can i write it?
Thanks

peroxide
  • 676
  • 1
  • 4
  • 17
  • Do you really need to do it on client side ? This seems to be more like a server generation matter ? 'cause i'm not sure about JS file inclusion but last time i had to do something like that i used jQuery that helped. – MaxouMask Nov 29 '10 at 14:14
  • Hi @maskime, i have to do it on the client side this time, i know that it is better to do it on server side. jquery can also help. – peroxide Nov 29 '10 at 14:16
  • Client-side can make sense if you want to load a module and not refresh a whole page and are not using iframes. – haylem Nov 29 '10 at 14:18

2 Answers2

2
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  if (x > 2){
     fileref.setAttribute("src", "/js/file1.js")
 }else{
     fileref.setAttribute("src", "/js/file2.js")
 }
 document.body.appendChild(fileref);
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
FatherStorm
  • 7,015
  • 1
  • 18
  • 25
  • Hi, this code doesn't shows an error but the file isn't loaded. – peroxide Nov 29 '10 at 14:29
  • @peroxide: it's because you create an element with document.createElement() but you don't actually had it to the DOM. On SO we tend to just give you snippets of code answering the core issue mentioned by the question, not give you a complete rundown. Read the links in my answer in the section "to read more on the subject" to understand the general problem and how to deal with it. – haylem Nov 29 '10 at 14:33
  • Note that if you are doing this at document parse time, the attempt to add an element into the end of the `` when that body hasn't finished loading yet will confuse browsers (especially IE which may give you the dreaded ‘Operation aborted’). For old-school parse-time loading there is always the messy `document.write`, or simply schedule this to happen when the document is ready. – bobince Nov 29 '10 at 14:40
  • (Also, you don't have to use the somewhat wordy `setAttribute`. `fileref.type=` and `fileref.src=` are fine.) – bobince Nov 29 '10 at 14:42
0

you can write:

if(conditon)
   $('body').append("<script src='whatever'><" + "/script>");
Daniel
  • 2,276
  • 3
  • 23
  • 34
  • @peroxide: user239427 is talking about jQuery here. See www.jquery.com. You'll need to help yourself a bit I'm afraid and read a bit on that to pick up. There's no native construct for JS imports built into the language itself. – haylem Nov 29 '10 at 14:30