简体   繁体   中英

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. If I were going to implement JavaScript from a HTML page, I would do:

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

import java.util.*

Is there a similar way in 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/

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:

  • The aforementioned script tag;
  • Compressing both files' source in a single file;
  • Using a modular loader such as 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.

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. Still, if you want to keep your .js files split and import them from another .js file, your best option is RequireJS .

Also, if you were using jQuery, you could use $.getScript and run the rest of your code inside $.getScript 's callback.


Since you're using jQuery, here's a jQuery-only solution for adding the qtip .js dynamically when needed and supplying :

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:

$(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. 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.

RequireJS is a better option if you need to include many .js files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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