开发者

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???

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>

开发者_如何学Python

I get error telling the variables are not defined and the functions(they are in external javascript files) are not defined

Thanks:)


you can dynamically load Javascript files. This is a good link. 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.


yeah its possible to do it by using the DOM to add the js file to the head of the document.

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

Of course you then have to tell your current JS file that the one you added has loaded. 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


Try this js loader http://www.dustindiaz.com/scriptjs/ I find it very convenient. 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. In addition to not causing problems with undefined variables, it also reduces the HTTP requests to 1 from 4.

Try using the closure compiler to merge your code into a single file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜