使用onclick加载js文件

时间:2014-06-25 07:43:01

标签: javascript html5

我有一个包含多个功能的javascript文件。

我在网上发现这个脚本允许我通过点击按钮来调用js文件。

假设js文件名为black.js,是否有更好的方法来编写此代码或其他允许我调用整个javascript文件的脚本,因为我有多个脚本,而且我无法结束脚本I调用

我试过了:

return false; 这是脚本:

var btn = document.getElementById('img');
var loaded = false;
btn.addEventListener('click', function(e) {
    if(loaded) return;
    loaded = true;
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = 'black.js';
    var first = document.getElementsByTagName('script')[0]; 
    first.parentNode.insertBefore(script, first);

    if(window.addEventListener) {
      script.addEventListener('load', function(e) {
        // now you can access the functions inside the JS file
      });
    } else {
      script.onreadystatechange = function() {
        if(this.readyState === "loaded" || this.readyState === "complete") {
          // access the functions in the JS file
          script.onreadystatechange = null;
        }
      };
    }
});

这是我的Javascript文件

var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];

imgCat.src =   'http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
    ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};

var mousedown = false;
$(function(){
    $("img").click(function(){
        ajax_request();
    });
});

ctx.strokeStyle = '#14890E';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
    arr = [];
    var pos = fixPosition(e, canvas);
    mousedown = true;
    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y);
    return false;
};

canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
    // coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
    if (mousedown) {
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
       arr.push([pos.x, pos.y])
    }
};

canvas.onmouseup = function(e) {
    mousedown = false;
    // $('#coords').html(JSON.stringify(arr, null, 2));
};


function fixPosition(e, gCanvasElement) {
    var x;
    var y;
    if (e.pageX || e.pageY) { 
      x = e.pageX;
      y = e.pageY;
    }
    else { 
      x = e.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = e.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    } 
    x -= gCanvasElement.offsetLeft;
    y -= gCanvasElement.offsetTop;
    return {x: x, y:y};
}

2 个答案:

答案 0 :(得分:0)

对IE8使用attachEvent,否则此脚本应该适用于所有“主流”浏览器。

btn.onclick = function (e) {
    // correction: the parameter that gets passed into the function
    // is an event object not the name of a file.

    var file = 'file_to_load.js';
    var f = document.createElement('script');

    f.onload = function(){
        // use the loaded script here
    };

    f.setAttribute('type', 'text/javascript');
    f.setAttribute('src', file);
    document.getElementsByTagName('head')[0].appendChild(f);
}

window.onload = function(){
    var b = document.getElementById('button'), f = 'script.js?12345';
    if(b.id == 'some-id') {
        b.onclick = function() {
            var s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.setAttribute('src', f);
            document.getElementsByTagName('head')[0].appendChild(s);
        }
    }
};

答案 1 :(得分:0)

我手头没有您的代码,但请尝试以下方法将角括号值替换为适当的代码。

// makes sure html has loaded before element query
// ommit if html has already loaded
window.onload = function(){

    var btn = document.getElementsByTagName('#<id_of_button>');
    btn.onclick = function (e) {

        var file = '<relative_path_to_file>.js';
        var f = document.createElement('script');

        f.onload = function(){
            // use the loaded script here if needed
        };

        f.setAttribute('type', 'text/javascript');
        f.setAttribute('src', file);
        document.getElementsByTagName('head')[0].appendChild(f);
    }
}

确保在文档加载完成之前声明window.onload(如果使用),否则代码将无法运行。