How to run/load a separate javascript file selectively from inside javascript?

前端 未结 4 398
生来不讨喜
生来不讨喜 2021-01-24 16:01

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 d

相关标签:
4条回答
  • 2021-01-24 16:32

    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);
    }
    
    0 讨论(0)
  • 2021-01-24 16:33
    var s = document.createElement("script");
    s.src="myscript.js";
    document.head.appendChild(s);
    

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

    0 讨论(0)
  • 2021-01-24 16:38

    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.

    0 讨论(0)
  • 2021-01-24 16:38

    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.

    0 讨论(0)
提交回复
热议问题