【问题标题】:Loading template images in requireJS module在 requireJS 模块中加载模板图像
【发布时间】:2014-07-27 00:16:09
【问题描述】:

我正在使用带有 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 类型 text/html 传输”,这是有道理的,但我不知道如何通过它。


我也乐于接受不同的方法来完成我的任务。

谢谢。

【问题讨论】:

  • 对我来说似乎是服务器配置问题。当您修改src 属性时,浏览器从服务器获取图像,服务器告诉浏览器这是一个text/html 资源。

标签: javascript requirejs requirejs-text


【解决方案1】:

正如插件文档所说:它有一些限制https://github.com/requirejs/text#xhr-restrictions

而且名称本身暗示其他资源不是文本的困难。

另一种方法是确定模块的脚本位置并向该位置的图像发出请求。从 RequireJS 的角度来看,这似乎违反直觉,但我似乎在 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';

我想你明白了。

可能的问题是优化版本。还不知道这种情况会发生什么。

【讨论】:

  • 非常感谢您的建议和 cmets。我离开了一段时间,同时决定停止在项目中一起使用 require js,由于没有时间,这个问题几乎没有解决。在这一点上我不能说哪种方法会奏效,但我 +1 表示你花时间写答案。
【解决方案2】:

使用来自this stack of plugins的图片插件。

这不是官方的,但应该做的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2014-12-15
    • 2013-08-24
    相关资源
    最近更新 更多