0

I want to load 2 external JS scripts within a script tag, is there a way to load 2 scripts with one document.write tag or do you have to declare it twice? Can't seem to find any answers.

document.write('<script src="js/scroll.js"><\/script>');
document.write('<script src="js/mobile.js"><\/script>');
4
  • are you sure you want to use document.write?
    – Luke
    Feb 2, 2011 at 18:56
  • I would avoid document.write. if you use document.createElement you can attach onload and onreadystatechange handlers to detect when the script has finished loading.
    – zzzzBov
    Feb 2, 2011 at 18:59
  • I was just searching for loading JS within a script and document.write seemed to come up the most, is it not the best method?
    – Yammi
    Feb 2, 2011 at 19:04
  • document.write is blocking. you can read more about it here. stevesouders.com/blog/2012/04/10/dont-docwrite-scripts
    – sean
    Apr 14, 2012 at 2:01

3 Answers 3

1
document.write('<script src="js/scroll.js"><\/script><script src="js/mobile.js"><\/script>');
1

Check out this way:

//JS CODE:
function include(path) 
{
   var e;
   e = window.document.createElement('script');
   e.setAttribute('src',path);
   window.document.body.appendChild(e);
}

include("js/scroll.js");    
include("js/mobile.js");
2
  • The advantage to a solution such as this is that it wont matter if the page has finished loading or not. If you use document.write and accidentally call the function after the page is done loading, you can brick your entire page.
    – zzzzBov
    Feb 2, 2011 at 19:01
  • Maybe, but he want to know otherway to include file. Maybe it is not the best or even good way, but it is other than document.write.
    – Robik
    Feb 2, 2011 at 19:05
1

Can you use jQuery?

jQuery("document").ready(function() {

   if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod'){

   document.write('<script src="js/scroll.js"><\/script><script src="js/mobile.js"><\/script>');

   }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.