简体   繁体   English

在js文件中包含外部js文件

[英]Including external js files in a js file

HI, 嗨,

I have a javascript lib which has a.js,b.js,c.js files....My logic is in d.js...How do I refer to a.js,b.js,c.js files in d.js??? 我有一个包含a.js,b.js,c.js文件的javascript库。...我的逻辑在d.js中...如何引用a.js,b.js,c.js文件在d.js中???

Is it possible to refer?? 可以参考吗?

I tried using 我尝试使用

document.write('<script type="text/javascript" src="a.js"></script>');

and

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

I get error telling the variables are not defined and the functions(they are in external javascript files) are not defined 我收到错误消息:未定义变量且未定义函数(它们在外部javascript文件中)

Thanks:) 谢谢:)

you can dynamically load Javascript files. 您可以动态加载Javascript文件。 This is a good link. 这是一个很好的链接。 http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html

However what I find more useful is to use PHP to render my javascript and in my php append all the javascript I need for a relevant page. 但是,我发现更有用的是使用PHP呈现我的JavaScript,并在我的PHP中附加我需要相关页面的所有JavaScript。

yeah its possible to do it by using the DOM to add the js file to the head of the document. 是的,可以通过使用DOM将js文件添加到文档的开头来实现。

    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.language="Javascript";
    newScript.charset="ISO-8859-1";
    newScript.src = 'yourfile.js';

headID.appendChild(newScript); headID.appendChild(newScript);

Of course you then have to tell your current JS file that the one you added has loaded. 当然,您必须告诉当前的JS文件已加载了您所添加的JS文件。 I do that by declaring a JS function in the current JS file and then calling it at the end of the one that has been dynamically loaded 为此,我在当前JS文件中声明了一个JS函数,然后在已动态加载的文件的末尾调用它

Try this js loader http://www.dustindiaz.com/scriptjs/ I find it very convenient. 试试这个js loader http://www.dustindiaz.com/scriptjs/我觉得很方便。 It has feature to manage dependencies, so you can give rules in which order scripts load. 它具有管理依赖项的功能,因此您可以给出加载脚本顺序的规则。

I would suggest merging all required files into a lib.js file. 我建议将所有必需的文件合并到lib.js文件中。 In addition to not causing problems with undefined variables, it also reduces the HTTP requests to 1 from 4. 除了不会引起未定义变量的问题外,它还将HTTP请求从4减少到1。

Try using the closure compiler to merge your code into a single file. 尝试使用闭包编译器将代码合并到单个文件中。

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

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