简体   繁体   English

如何在JavaScript文件中包含库?

[英]how to include a library in a JavaScript file?

In other to separate the HTML pages from the JavaScript implementation, I created different .js files for every set of functionalities on my website. 除了将HTML页面与JavaScript实现分开之外,我还为网站上的.js功能创建了不同的.js文件。 If I were going to implement JavaScript from a HTML page, I would do: 如果要从HTML页面实现JavaScript ,则可以执行以下操作:

<script type="text/javascript" src="path/to/javascript/jquery.qtip.js"></script>

However, how would I go over including that library, jquery.qtip.js into a .js file, like heatmap.js ? 但是,我将如何将那个库jquery.qtip.js.js文件(如heatmap.js I'm asking that because I'm getting the following error from firebug: 我问这是因为我从萤火虫中收到以下错误:

TypeError: $("mytable td").qtip is not a function
[Break On This Error]   

style : 'ui-tooltip-tipsy ui-tooltip-shadow'

If I were in java, I would include an external library or class as: 如果我使用的是Java,我将包含一个外部库或类,如下所示:

import java.util.*

Is there a similar way in JavaScript? JavaScript中有类似的方法吗?

function heatmap()
{
    var input = document.getElementById("heatmap").value;

    // TAKE THE HEATMAP HTML OBJECT AND MAKE A POST TO THE BACKEND
    $("#heatmap").empty().html(baseurl + "/images/loader.gif/>");
    $.post(baseurl + "index.php/heatmap/getMatrix",
        {
            input : input.toString()
        },

        function(answer){
            var list = eval('(' + answer + ')');
            var temp = list.split(" ");
            makeTable(temp);

            $(document).ready(function(){
                $('mytable td').qtip({
                overwrite : false,      // make sure it can' be overwritten
                content : {
                    text : function(api){
                    var msg = "Interaction: " + $(this).html(); 
                    return msg;
                    }
                },
                position : {
                   my : 'top left',
                   target : 'mouse',
                   viewport : $(window),    // keep it on screen at all time is possible
                   adjust : {
                    x : 10, y : 10
                   }
                },

                hide : {
                   fixed  : true        // helps to prevent the tooltip
                },
                style : 'ui-tooltip-tipsy ui-tooltip-shadow' 
                });
            });
        });

}

** * ** * ** * * ADDING MAKETABLE FUNCTION * ** * ** * ** * * ** * ** * ** * *添加可修改的功能* ** * ** * ** * *

function makeTable(data)
{
    var row = new Array();
    var cell = new Array();

    var row_num = 18;
    var cell_num = 16;

    var tab = document.createElement('table');
    tab.setAttribute('id', 'mytable');
    tab.border = '1px';

    var tbo = document.createElement('tbody');

    for(var i = 0; i < row_num; i++){
            row[i] = document.createElement('tr');

            var upper = (i+1)*16;
            var lower = i*16;
            for(var j = lower; j < upper; j++){
                cell[j] = document.createElement('td');
                //cell[j].setAttribute('class', 'selector');
                if(data[j] != undefined){
                    var index = Math.round(parseFloat(data[j])*100) / 100;
                    var count = document.createTextNode(index);
                    cell[j].appendChild(count);

                    /* specify which color better suits the heatmap */
                    if(index <= -4){
                        cell[j].style.backgroundColor = '#FF0000';
                    }
                    else if(index > -4 && index <= -3.5){
                        cell[j].style.backgroundColor = "#FF2200";
                    }
                    else if(index > -3.5 && index <= -3.0){
                        cell[j].style.backgroundColor = "#FF2222";
                    }
                    else if(index >= -3.0 && index < -2.5){
                        cell[j].style.backgroundColor = "#FF3311";
                    }
                    else if(index >= -2.5 && index < -2.0){
                        cell[j].style.backgroundColor = "#FF5500";
                    }
                    else if(index >= -2.0 && index < -1.5){
                        cell[j].style.backgroundColor = "#FF8811";
                    }
                    else if(index >= -1.5 && index < -1.0){
                        cell[j].style.backgroundColor = "#FFAA22";
                    }
                    else if(index >= -1.0 && index < -0.5){
                        cell[j].style.backgroundColor = "#FFCC11";
                    }
                    else if(index >= -0.5 && index < 0){
                        cell[j].style.backgroundColor = "#FFCC00";
                    }
                    else if(index == 0){
                        cell[j].style.backgroundColor = "#000000";
                    }
                    else if(index > 0 && index < 0.5){
                        cell[j].style.backgroundColor = "#FF8800";
                    }
                    else if(index >= 0.5 && index < 1.0){
                        cell[j].style.backgroundColor = "#FFBB00";
                    }
                    else if(index >= 1.0 && index < 1.5){
                        cell[j].style.backgroundColor = "#FFFF00";
                    }
                    else if(index >= 1.5 && index < 2.0){
                        cell[j].style.backgroundColor = "#00CC00";
                    }
                    else if(index >= 2.0 && index < 2.5){
                        cell[j].style.backgroundColor = "#008800";
                    }
                    else if(index >= 2.5 && index < 3.0){
                        cell[j].style.backgroundColor = "#006600";
                    }
                    else if(index >= 3.0 && index < 3.5){
                        cell[j].style.backgroundColor = "#004400";
                    }
                    else{

                    }
                    row[i].appendChild(cell[j]);
                }
            }

            tbo.appendChild(row[i]);
        }

        tab.appendChild(tbo);
        document.getElementById('mytable').appendChild(tab);
}

I think you are looking for a script loader like http://requirejs.org/ 我认为您正在寻找http://requirejs.org/之类的脚本加载器

require(["jquery", "jquery.qtip.js", ...], function($) {
    // do something when loaded
});

You already know how to include .js files with script tags, so you have 3 options: 您已经知道如何在script标签中包含.js文件,因此您有3种选择:

  • The aforementioned script tag; 前面提到的script标签;
  • Compressing both files' source in a single file; 将两个文件的源压缩到一个文件中;
  • Using a modular loader such as RequireJS . 使用模块化加载器,例如RequireJS

There's no simple built-in function to halt the execution of the script while you load another script's source in JavaScript such as PHP's include / require or Java's import or C's include , because JavaScript's script loading is asynchronous -- the scripts execute in the order you include them in the page, but they won't wait to load a dynamically added script. 在JavaScript中加载另一个脚本源(例如PHP的include / require或Java的import或C的include ,没有简单的内置函数来停止脚本的执行,因为JavaScript的脚本加载是异步的-脚本按您执行的顺序执行将其添加到页面中,但它们将等不及加载动态添加的脚本。

Note that the first and third options make extra HTTP requests, so if your script always requires such a function, you may include it in your script itself to reduce HTTP requests. 请注意,第一个和第三个选项会发出额外的HTTP请求,因此,如果脚本始终需要这样的功能,则可以将其包含在脚本本身中以减少HTTP请求。 Still, if you want to keep your .js files split and import them from another .js file, your best option is RequireJS . 不过,如果您希望将.js文件分开并从另一个.js文件导入,则最好的选择是RequireJS

Also, if you were using jQuery, you could use $.getScript and run the rest of your code inside $.getScript 's callback. 另外,如果您使用的是jQuery,则可以使用$.getScript并在$.getScript的回调中运行其余代码。


Since you're using jQuery, here's a jQuery-only solution for adding the qtip .js dynamically when needed and supplying : 由于您使用的是jQuery,因此这是一个仅jQuery的解决方案,用于在需要时动态添加qtip .js并提供:

if (!$().qtip) //if qtip is not included/loaded into the page yet
    $.getScript('http://craigsworks.com/projects/qtip2/packages/latest/jquery.qtip.min.js', heatmap);
else heatmap();

Fiddle 小提琴

Of course, you can just use the $.getScript directly inside the DOM ready event or anywhere in the page as well: 当然,您可以直接在DOM ready事件中或页面中的任何位置直接使用$.getScript

$(document).ready(function() {
    $.getScript('http://craigsworks.com/projects/qtip2/packages/latest/jquery.qtip.min.js');
});

Beware that $.getScript will be asynchronous, so you have to wrap the rest of the code which depends on this script inside its callback. 注意$.getScript将是异步的,因此您必须将依赖于此脚本的其余代码包装在其回调中。 There are ways to set this as a synchronous ajax call, but it could freeze up/slow down the loading of your page, hence forcing it to be synchronous is unrecommended. 有多种方法可以将其设置为同步ajax调用,但是它可能会冻结/减慢页面的加载速度,因此建议不要强制页面同步。

RequireJS is a better option if you need to include many .js files. 如果您需要包含许多.js文件,则RequireJS是更好的选择。

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

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