简体   繁体   English

在 .js 文件中使用外部 javascript 文件

[英]Using external javascript files in a .js file

I would like to use an external javascript file in another javascript file.我想在另一个 javascript 文件中使用外部 javascript 文件。 For example, I could store all my global variables in a globals.js file and then call then from the website logic logic.js.例如,我可以将所有全局变量存储在 globals.js 文件中,然后从网站逻辑 logic.js 调用。 Then in the index.html, i would insert the tag.然后在 index.html 中,我会插入标签。 How do I use the globals.js inside the logic.js?如何在 logic.js 中使用 globals.js?

Javascript doesn't have any implicit "include this other file" mechanisms, like css's @include. Javascript 没有任何隐式的“包含此其他文件”机制,例如 css 的 @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.如果保证在逻辑文件中的任何内容启动之前全局变量可用,则可以在调用 init() 或任何函数之前执行慢速轮询循环以查看某些特定变量是否可用。

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.编辑:实际上,这可能不适用于您的目的,因为 global.js 变量在 logic.js 完成之前无法访问。 You may be able to wrap logic.js in a function that is called after global.js loads.您可以将 logic.js 包装在一个在 global.js 加载后调用的函数中。 Otherwise I don't think there is a way to do what you're asking.否则我认为没有办法做你所要求的。

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; }

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.只需在需要引用包含的 js 文件中的某些内容之前使用该行。

只需确保在您的 index.html 中引用了这两个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM