How to run/load a separate javascript file selecti

2020-04-21 06:43发布

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?

标签: javascript
4条回答
一纸荒年 Trace。
2楼-- · 2020-04-21 07:22
var s = document.createElement("script");
s.src="myscript.js";
document.head.appendChild(s);

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

查看更多
家丑人穷心不美
3楼-- · 2020-04-21 07:27

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);
}
查看更多
Fickle 薄情
4楼-- · 2020-04-21 07:30

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 recommend either of those options. It's probably going to get really problematic maintaining separate files. Instead of loading completely 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 combination 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 comes time to fix or maintain.

查看更多
霸刀☆藐视天下
5楼-- · 2020-04-21 07:43

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.

查看更多
登录 后发表回答