我将文本插件与 requireJS 一起使用,以便将一些 html 加载到页面中。 我已经定义了一个负责此的模块:
define(['jquery', 'text!/path/to/template/template_name.html'], function($, rciTpl){
在模块内部我有一个方法,在从 ajax 调用广告项目到 DOM 接收数据后:
var buffer = $.map(data, function(d, i){
//clone the template;
var tpl = template.clone();
//set the url
tpl.find('a.lt, a.la').attr('href', d.url);
//set the title
tpl.find('a.lt').text(d.title);
//return the raw node
return(tpl.get());
});
$('#myContainer').append(buffer);
目前一切正常。当我想将图像动态添加到我的模板时出现问题。像这样:
tpl.find('img').attr('src', 'item_img_path.svg');
我在浏览器的控制台中得到的错误是:“资源解释为图像,但使用 MIME 类型文本/html 传输”,这是有道理的,但我不知道如何通过它。
我也愿意接受不同的方法来完成我的任务。
谢谢。
最佳答案
正如插件文档所说:它有一些限制 https://github.com/requirejs/text#xhr-restrictions
这个名称本身暗示了其他非文本资源的困难。
另一种方法是确定模块的脚本位置并向该位置的图像发出请求。从 RequireJS 的 Angular 来看,这似乎是违反直觉的,但我已经将其与 OpenLayers
一起使用了OpenLayers 是我的应用程序的依赖项。我在 shim
配置中设置了它。一些它如何找到它的图像和样式。阅读它的代码我了解到它使用了这个所谓的 getScriptLocation
方法:
_getScriptLocation: (function() {
var r = new RegExp("(^|(.*?\\/))(OpenLayers[^\\/]*?\\.js)(\\?|$)"),
s = document.getElementsByTagName('script'),
src, m, l = "";
for(var i=0, len=s.length; i<len; i++) {
src = s[i].getAttribute('src');
if(src) {
m = src.match(r);
if(m) {
l = m[1];
break;
}
}
}
return (function() { return l; });
})()
查看它如何确定要使用的 css:
this.theme = OpenLayers._getScriptLocation() + 'theme/default/style.css';
我想你明白了。
可能的问题是优化版本。还不知道在那种情况下会发生什么。
关于javascript - 在 requireJS 模块中加载模板图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288142/