gpt4 book ai didi

javascript - 使用 Rawgit 获取 Javascript 文件

转载 作者:行者123 更新时间:2023-11-30 15:28:46 24 4
gpt4 key购买 nike

我正在尝试通过 Ajax 在我的网站中包含一个 JS 文件,方法是使用 Rawgit 从我的 GitHub 存储库之一获取它。出于某种原因,当我使用开发或生产 URL 时它不起作用,但是当我直接从 Github 使用我的文件的原始版本时,问题就停止了。当我使用 CSS 文件的开发 URL 时,我没有遇到任何问题。有谁知道为什么会这样?

这是我的代码:

$.get("https://rawgit.com/Larpee/The-Khan-Quiz/master/game.js", function (game) {
var sketchProc = function (processingInstance) {
with (processingInstance) {
size(400, 400);
frameRate(30);
eval(game);
}
};

var canvas = document.getElementById("game");
var processingInstance = new Processing(canvas, sketchProc);
});

更新:我认为问题的发生是因为 GitHub(不是 Rawgit)将文件作为 .txt 文件提供,而 RawGit 作为 .js.

我仍然希望收到关于为什么获取带有 .js 扩展名的 JavaScript 文件不起作用的解释

最佳答案

对于 RawGit,你得到 content-type: application/javascript;charset=utf-8 正如预期的那样,GitHub 给出了 Content-Type: text/plain;字符集=utf-8。这似乎是唯一的区别。

我检查了你的示例,发现当使用 RawGit(并获得脚本响应)时,success 回调根本不会执行,但使用 GitHub 时它会(添加一个 console .log('foo'); 语句,例如。我还发现 eval() 在你的脚本上运行会抛出异常:

Uncaught ReferenceError: createFont is not defined

我自己用语法正确的占位符 JS 文件创建了一个 repo,在这种情况下,RawGit 和 GitHub 上 $.get()success 回调都执行了, 后来添加了对未定义名称的引用,这导致对 RawGit URL 的调用无法执行其回调。

教训?当您使用 $.get() 获取脚本时,它实际上会立即执行,如果 eval() 失败,那么一切都将无声地结束。这由 jQuery getScript load vs execution 支持,这也意味着这种(在我看来)处理脚本数据的疯狂方式在 2.1.0 版中结束了。

这让我建议,除了修复脚本之外,您还应该使用 $.getScript()(不确定是否必须确保结果 header 具有 application/javascript ), 或者用 JS 显式插入脚本元素并有一个 onload 回调:

(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function(){
// remote script has loaded
};
script.src = '[RawGit URL]';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));

此外,您使用的 with block 应该变成:

var sketchProc = function (processing) { 
processing.size(400, 400);
processing.frameRate(30);
}

var canvas = $('#game'); // use jQuery since you have it
var processingInstance = new Processing(canvas, sketchProc);

// game code now manipulates `processingInstance`
// either directly in scope (or even better as object with parameter)
processingInstance.draw = function () {
var processing = this;
// if your code originally used `processing` throughout,
// do this so that it refers to the specific instance you've created
// ...
}
processingInstance.loop();
// if initialized without a `.draw()` method like above, you need to start the loop manually once there is one

Processing.js 文档有很多示例,这些示例基本上都是 Java 的,需要进行小的修改才能正确处理 JS 范围。伤心!

关于javascript - 使用 Rawgit 获取 Javascript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com