How to runload a separate javascript file selectively from inside javascript? - Stack Overflow

I have 3 JavaScript files that I would like to load from an index.html file. I'm choosing among th

I have 3 JavaScript files that I would like to load from an index.html file. I'm choosing among them by using if statements which I only know how to do in JavasSript. However when in a JavaScript body, it doesn't look like I can say something like:

<script type="text/javascript">
if(window.innerHeight == 800)
     <script type="text/javascript" charset="utf-8" src="storybook.js"></script>

Is there a function or something I could use to execute the JavaScript file after the conditional?

I have 3 JavaScript files that I would like to load from an index.html file. I'm choosing among them by using if statements which I only know how to do in JavasSript. However when in a JavaScript body, it doesn't look like I can say something like:

<script type="text/javascript">
if(window.innerHeight == 800)
     <script type="text/javascript" charset="utf-8" src="storybook.js"></script>

Is there a function or something I could use to execute the JavaScript file after the conditional?

Share Improve this question edited Jan 8, 2013 at 4:41 ErikE 50.3k23 gold badges156 silver badges200 bronze badges asked Jan 8, 2013 at 4:21 user1776524user1776524 1271 gold badge2 silver badges9 bronze badges 2
  • What exactly do you want to do? From the little snippet it seems that you want to display something as a storybook given the size of the window. What are the other options? What are the other options? perhaps you don't need to choose different javascripts. – Ricardo Marimon Commented Jan 8, 2013 at 4:30
  • 1 Typically, you don't need to choose which .js file(s) to load. Instead, load all files and choose which function(s) are appropriate, or have generalized functions to which parameters can be passed to determine their detailed behaviour. Unless there's a pelling reason to load .js files selectively (eg they are third party files over which you have no control), then you have opted for a poor architecture. – Beetroot-Beetroot Commented Jan 8, 2013 at 4:32
Add a ment  | 

4 Answers 4

Reset to default 4

UPDATE

Things were already changing when I initially wrote this answer, but they have continued to change to the point where this answer is not somewhat obsolete. Please consult The 2014 Guide to Responsive Web Design as there are now ways to use media queries in a stylesheet to get the responsive layout you're looking for. Frameworks like Foundation and Bootstrap now offer responsive layouts and take care of a lot of the heavy lifting for you, so you can spend time designing your site instead of coding its plumbing.

ORIGINAL ANSWER

There are a few ways, but here's one (from dynamically loading an external JavaScript or CSS file, found by Google searching for "dynamic load javascript"):

function loadjsfile(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);
   }
}

loadjsfile("storybook.js"); //dynamically load and add this .js file

Another way is, instead of dynamically loading the file, just load all the content you want in one file. Then, call the correct script. While this could be criticized for loading the entire file, what happens if your user changes his screen size? Maybe you want both resources loaded. Changing screen size is not so far-fetched as people resize windows, or even move a window to a different monitor with a different resolution.

// storybook800.js
function for800() {
   return {
      // all your module's stuff
   };
};

// storybook1600.js
function for1600() {
   return {
      // all your module's stuff
   };
};

// main document
var storybook;
if (window.innerHeight === 800) {
   storybook = for800();
} elseif (window.innerHeight === 1600) {
   storybook = for1600();
}

However, I don't really remend either of those options. It's probably going to get really problematic maintaining separate files. Instead of loading pletely different files, just detect within your code. Either pass in the window.innerHeight parameter or better, just detect it in your javascript file:

//storybook.js
function mystorybook() {
   if (window.innerHeight === 800) {
      //do something appropriate.
   }
};

If that seems painful, add some helper functions. For example, create a function that expects an object with various keys that contain size-dependent functions to run for different sizes. It might be called something like this:

doSomethingSizeSensitive({
   800: function() {
   },
   1024: function() {
   },
   1600: function() {
   }
});

Then you could write code in that function that does the best job of selecting the correct result based on the current screen size and the passed in object keys. Instead of doSomethingSizeSensitive actually running the functions, it could return the appropriate function or value you passed in, which you then use or store:

var myaction = getSizeSensitiveFunction({
   800: function() {
   },
   1024: function() {
   },
   1600: function() {
   }
});
myaction(); // for the rest of the lifecycle of the page, it does the right thing.

You could have your function return anything--not just functions, but also values as well. And what if the screen size is 1280 or 1528 or some other strange size? You'll want to pick functionality intelligently. Think about how to abstract away the part that has to be different, by encoding it in objects or in detecting-style-functions that are called from other code, so the rest of your code can all be the same.

Maybe you should have a whole setup object:

sizedata = {
   800: {
      something1: function() {},
      value1: 'small'
   },
   1600: {
      something2: function() {},
      value2: 'large'
   },
};

In bination with a function to correctly choose the correct sizedata sub-object, now you're in golden shape any time you want to tweak something or add a new screen size. It's all in one place! You are in heaven when it es time to fix or maintain.

By appending the script to the document.

if(window.innerHeight == 800){
    var script = document.createElement("script");
    script.src = "storybook.js";
    document.getElementsByTagName("head")[0].appendChild(script);
}
var s = document.createElement("script");
s.src="myscript.js";
document.head.appendChild(s);

Oh man, so many same answers at the same time.

I'm new to javascript but i have an idea you can set id to just like <header id='h'></header> then you can append your script to header by using this code:

var h = document.getElementById('h');
var scripts = document.createElement('script');
switch(window.innerHeight){
    case 800:
      scripts.src = 'storybook.js';
      scripts.type = 'text/javascript';
      break;
}
h.appendChild(scripts);

You can change scripts source by add more case. Thanks for reading.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745333193a4622981.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信