Using external javascript files in a .js file

前端 未结 5 830
梦毁少年i
梦毁少年i 2020-12-03 01:45

I would like to use an external javascript file in another javascript file. For example, I could store all my global variables in a globals.js file and then call then from t

相关标签:
5条回答
  • 2020-12-03 01:57

    You can also do something like this:

    $(document).ready(function(){
        $('body').append($('<script src="/path/to/script/foo.min.js"></script>'));
    });
    

    Just use that line before you need to reference something in the included js file.

    0 讨论(0)
  • 2020-12-03 01:59

    Javascript doesn't have any implicit "include this other file" mechanisms, like css's @include. You just have to list your globals file before the logic file in the tags:

     <script type="text/javascript" src="globals.js" />
     <script type="text/javascript" src="logic.js" />
    

    If guaranteeing that the globals are available before anything in the logic file fires up, you can do a slow polling loop to see if some particular variable is available before calling an init() or whatever function.

    0 讨论(0)
  • 2020-12-03 02:19
    function loadExternalJS(TARGET_URL){
    var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    xhr.open('GET', TARGET_URL, false);
    xhr.send(null);
    var code = xhr.responseText;
    var dScript = document.createElement('script');
    try {
    dScript.appendChild( document.createTextNode(parsed) );
    document.body.appendChild(dScript);
    } catch(e) {
    dScript.text = parsed;
    document.getElementsByTagName('head')[0].appendChild(dScript);
    }
    xhr = null;
    
    0 讨论(0)
  • 2020-12-03 02:20

    Just make sure both files are referenced in your index.html.

    0 讨论(0)
  • 2020-12-03 02:23
    document.write('<script type="text/javascript" src="globals.js"></script>');
    

    Edit: Actually, this probably won't work for your purposes, as global.js variables won't be accessible until logic.js completes. You may be able to wrap logic.js in a function that is called after global.js loads. Otherwise I don't think there is a way to do what you're asking.

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