[英]Letting a user use a compiled RequireJS Widget after it has loaded
I'm writing a JS Widget using RequireJS. 我正在使用RequireJS编写JS Widget。 After finishing the widget I'm compiling it with r.js and Almond.
完成小部件后,我将使用r.js和Almond对其进行编译。 All goes well - but I couldn't find an easy way to let the user use the widget without using RequireJS himself - as the widget code loads async (RequireJS uses AMD).
一切顺利-但是我找不到一种简单的方法让用户不用自己使用RequireJS就使用小部件-因为小部件代码会异步加载(RequireJS使用AMD)。
What I'm doing now is busy waiting for the widget code to load and using it only after detecting it has loaded. 我现在正在做的事情是等待窗口小部件代码加载,并仅在检测到已加载后才使用它。 This is not very user-friendly.
这不是非常用户友好。
Is there a way to let just do something like this? 有没有办法让自己做这样的事情?
var widget = new Widget();
instead of doing busy wait like: 而不是像这样忙着等待:
count = 0;
function loadWidget() {
if (typeof Widget != 'undefined') {
var p1 = new Widget();
p1.render();
} else {
if (count > 10) {
console.log('Failed to load the Widget');
return false;
}
setTimeout(loadWidget, 50);
count++;
}
}
$(document).ready(function() {
loadWidget();
});
Thanks! 谢谢!
EDIT: 编辑:
my build.js 我的build.js
({
name: './lib/almond.js',
out: './deploy/sdk.min.js',
baseUrl: '.',
optimize: 'uglify2',
mainConfigFile: 'sdk.js',
include: ['sdk'],
wrap: true
})
Code on the web page (assume no other script tags on page): 网页上的代码(假设页面上没有其他脚本标签):
<script src="mywidget.js" data-main="scripts/sdk" id="mywidget"></script>
No sure if the 'data-main' is really required as the js is compiled. 不确定在编译js时是否真的需要“ data-main”。
You need to follow the instructions provided with Almond . 您需要遵循Almond随附的说明。 To summarize the essential points what is in the doc there, what you need in your build config the following configuration:
总结要点,这里的文档是什么,构建配置中需要以下配置:
wrap: {
startFile: 'path/to/start.frag',
endFile: 'path/to/end.frag'
}
And the start.frag
should be: 并且
start.frag
应该是:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.Widget = factory();
}
}(this, function () {
and the end.frag
: 和
end.frag
:
return require('main');
}));
The end fragment calls require
in its synchronous form, which is really synchronous in this case (and not the pseudo-synchronous sugar that can be used by RequrieJS itself). 结束片段调用
require
采用其同步形式,在这种情况下,它实际上是同步的(而不是RequrieJS本身可以使用的伪同步糖)。
I've tried this before. 我以前尝试过 It works.
有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.