在另一个JS文件中包含JS文件

时间:2014-02-13 16:11:29

标签: javascript

我想知道是否有办法在另一个js文件中包含js文件,以便您可以引用它。我要求的是PHP中的JS等同于include()

我见过很多人推荐这种方法作为例子:

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

但我不确定这是否与include()

相同

2 个答案:

答案 0 :(得分:2)

结帐http://requirejs.org/。您可以定义(AMD)模块并在其他模块中引用它们

define(["path/to/module1", "path/to/module1")], function(Module1, Module2) {
    //you now have access
});

答案 1 :(得分:1)

不要使用document.write,如果页面已经写好,它可能会删除整个页面。你可以写一些简单的东西:

var jsToInclude = document.createElement('script');
jsToInclude.type = 'type/javascript';
jsToInclude.src = '/dir/somefile.js'; //  path to the js file you want to include
var insertionPointElement = document.getElementsByTagName('script')[0]; // it could be the first javascript tag or whatever element 
insertionPointElement.parentNode.insertBefore(jsToInclude, insertionPointElement);
相关问题