When does a dynamically loaded JavaScript library become available?

前端 未结 5 511
遥遥无期
遥遥无期 2021-01-18 19:37

I wrote JavaScript library to use FileSaver.js and its associated libraries. However, I don\'t want to always load FileSaver.js whenever someone wants to use my library. And

相关标签:
5条回答
  • 2021-01-18 19:54

    the Holistic solution is to use a module system. AMD is (in-my-just-an-observation-please-dont-start-a-holy-war-opinion) probably the most commonly used system for browser async code loading. AMD is just a spec, but something like require.js is a very popular tool for using AMD modules.

    The idea being that you can define dependencies between your modules, and require.js will go fetch them if need be. The general idea is to mimic the import/namespace functionality of other languages (like java, C#, or python). "code sharing" i think is the term?

    simply put you have all your code in a callback function that runs once the dependencies are loaded, so you can be sure the needed objects and methods are present.

    update 2015

    just an addendum. while the info above is still correct, front end code management is moving quickly toward solutions like Webpack and Browserify, which bundle and concatenate code of any module type and both have dynamic code loading capabilities (webpack calls this code splitting). That coupled with the exponential growth of npm for dependency management is beginning to make AMD less relevant.

    0 讨论(0)
  • 2021-01-18 19:57

    So I agree with the AMD comment (can't put code blocking into comments meh...)

    Here's what I do for FileSaver.js

    First in my requirejs config / main.js :

    (function() {
        // REMEMBER TO DUPLICATE CHANGES IN GRUNTFILE.JS
        requirejs.config({
            paths: {
                "jquery": "PATH/jquery.min", // NO .js
                "lib.filesaver" : "PATH/FileSaver", // NO .js
                "shim.blob" : "PATH/Blob" // NO .js
            },
            shim: {
                "lib.filesaver": {deps: ["shim.blob"]}
            }
        });
    
        define([
            "jquery"
        ], function(
            $
            ) {
                $(document).ready(function() {
                    // start up code...
                });
            return {};
            });
    })();
    

    Then I place the Blob.js/jquery and Filersaver in correct places

    I also created a IEShim for pre IE10

    define([], function () {
        /**
         * @class IEshims
         * container for static IE shim functions
         */
        var IEShims = {
            /**
             * saveFile, pops up a built in javascript file as a download
             * @param {String} filename, eg doc.csv
             * @param {String} filecontent eg "this","is","csv"
             */
            saveAs: function (filename, filecontent, mimetype ) {
                var w = window.open();
                var doc = w.document;
                doc.open( mimetype,'replace');
                doc.charset = "utf-8";
                doc.write(filecontent);
                doc.close();
                doc.execCommand("SaveAs", null, filename);
            }
        };
        return IEShims;
    });
    

    And lastly when I want to use Filesaver make it required (along with IEShim for bad browsers)

    define([
    "lib.filesaver",
    "IEShims"
    ],
    function (
        FileSaver, // it's empty, see saveAs global var
        IEShims
        ) {
    ...
        var fileName = "helloworld.txt";
        var fileContents = "Me haz file contents, K Thx Bye";
        var mimeType = "text/plain";
        if(saveAs) {
            var blob = new Blob(
                [fileContents],
                {type: mimeType + ";charset=" + document.characterSet}
            );
            saveAs(blob, fileName);
        } else {
            IEShims.saveAs(fileName, fileContents,mimeType );
        }
        ...
    };
    
    0 讨论(0)
  • 2021-01-18 19:58

    Use Head.js: http://headjs.com/

    It will load scripts on demand.

    0 讨论(0)
  • 2021-01-18 20:04

    The simplest answer is to put your code in the onload handler of the script tag you create:

    <script>
      var firstScript = document.getElementsByTagName('script')[0],
          js = document.createElement('script');
      js.src = 'https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js';
      js.onload = function () {
        // do stuff with your dynamically loaded script
        snowStorm.snowColor = '#99ccff';
      };
      firstScript.parentNode.insertBefore(js, firstScript);
    </script>

    Loading scripts dynamically this way is done by Facebook.

    0 讨论(0)
  • 2021-01-18 20:10

    Alright, what you need to do is listen for the script to finish loading. Unfortunately there are some bugs with this code for ie<7.

    This is the way Mootools Asset.javascript loads scripts and calls a callback when its complete:

    var loadScript = function (source, properties) {
        properties || (properties = {});
        var script = document.createElement('script');
        script.async = true;
        script.src = source;
        script.type = 'text/javascript';
        var doc = properties.document || document, load = properties.onload || properties.onLoad;
        return delete properties.onload, delete properties.onLoad, delete properties.document, 
        load && (script.addEventListener ? script.addEventListener("load", load) : script.attachEvent("readystatechange", function() {
            [ "loaded", "complete" ].indexOf(this.readyState) >= 0 && load.call(this);
        })), script.set(properties).appendChild(doc.head);
    }
    

    Now in loadImage you can load the file library as follows:

    function createImage(image, name) {
      function createImg() {
          // now do the saveImage code
      }
      if (typeof(saveAs) !== 'function') {
         loadScript("FileSaver.js", {onLoad: createImg});//load library
      }
      else {
         createImg();
      }
    }
    

    Should work on most browsers.

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