[英]Including JS file in another JS file
我想知道是否有辦法在另一個js文件中包含一個js文件,以便您可以引用它。 我要求的是JS中與JS相當的include()
。
我見過很多人推薦這種方法作為例子:
document.write('<script type="text/javascript" src="globals.js"></script>');
但我不確定這是否與include()
相同
查看http://requirejs.org/ 。 您可以定義(AMD)模塊並在其他模塊中引用它們
define(["path/to/module1", "path/to/module1")], function(Module1, Module2) {
//you now have access
});
不要使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.