从另一个引用javascript库

时间:2012-03-21 20:47:19

标签: external javascript

我刚刚开始定义和实现外部javaScript库,我对这些规则感到有些困惑。以下是三个文件“top.js”,“bottom.js”和“ref.html”的内容。文件“bottom.js”包含对“top.js”的引用,文件“ref.html”包含对“bottom.js”的引用。在“ref.html”中,我试图通过直接调用函数来访问“top.js”中的函数,并通过“bottom.js”中的另一个函数调用该函数,这两种方法似乎都不起作用。任何建议将不胜感激。

topTest.js:

function top_test() {
alert('Test from top');
}

bottom.js

function bottom() {
alert("bottom");
top_test();
}

loadScript('topTest.js');    // Call function (function declarations are evaluated
                     //   before the rest of the code, so this works)

function loadScript(file_name) {
var newScript = document.createElement('script');
var scripts = document.getElementsByTagName('script');

// Reference to the latest (this) <script> tag in the document
scripts = scripts[scripts.length-1];

// Set target
newScript.src = file_name;

// Clean-up code:
newScript.onload = newScript.onerror = function() {
    this.parentNode.removeChild(this);
};

// Insert script in the document, to load it.
scripts.parentNode.insertBefore(newScript, scripts);

}

ref.html

<html>
<head>
<script type="text/javascript" src="bottom.js"></script>
</head>
<body>
test
<script type="text/javascript">
bottom();
top();
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

必须从<script>文件中删除.js代码。

这些标记在HTML文档中仅需要 ,用于将内容的一部分标记为脚本。 JavaScript文件的整个内容都是JavaScript,因此添加<script>标记没有任何意义,因此无效。

要在<head>的脚本中包含JavaScript,您可以使用库,或使用以下方法之一:

使用<script>创建document.createElement标记,然后在文档中插入脚本。 bottom.js

的示例
function bottom() {
    alert("bottom");
    top();
}
loadScript('top.js');    // Call function (function declarations are evaluated
                         //   before the rest of the code, so this works)

function loadScript(file_name) {
    if (document.readyState === 'loading') { // Chrome
        document.write('<script src="' + file_name.replace(/"/g, '&quot;') + '"></script>');
        return;
    }
    var newScript = document.createElement('script');
    var scripts = document.getElementsByTagName('script');

    // Reference to the latest (this) <script> tag in the document
    scripts = scripts[scripts.length-1];

    // Set target
    newScript.src = file_name;

    // Clean-up code:
    newScript.onload = newScript.onerror = function() {
        this.parentNode.removeChild(this);
    };

    // Insert script in the document, to load it.
    scripts.parentNode.insertBefore(newScript, scripts);
}

答案 1 :(得分:0)

请勿在{{1​​}}个文件中使用html标记。只是简单的JavaScript代码

相关问题