How do I load Sentry before the main JS bundle loads? - vue.js

I use Sentry to track client-side errors. However, I loaded my web app in the Edge browser today only to find a blank page. Edge raised a TextEncoder is not defined error because one of the libraries in my bundle referenced TextEncoder which it does not support. Sentry did not report the error because the error occurred before Sentry was initialized.
I use vue-cli to create a Vue project with Sentry being initialized near the top of the main file:
import { init } from '#sentry/browser';
import { environment } from '#/constants';
import { Vue as VueIntegration } from '#sentry/integrations';
export default function(Vue) {
const debug = environment !== 'production';
init({
dsn: 'redacted',
environment,
debug,
integrations: [new VueIntegration({ Vue, logErrors: debug })],
});
}
I've been thinking of initializing Sentry manually with a script tag near the start of the <body> tag. However, the fact that I use the VueIntegration plugin complicates things. Would it be safe to initialize Sentry twice? Once before the main bundle loads and once as I'm doing in the example above?
I noticed there's something in the docs about managing multiple Sentry clients but I'm not sure if that's relevant to my specific case.
One idea I have is just a barebones window.onerror hook before anything else loads but I'm not really sure how to interact with Sentry without pulling in their #sentry/browser package. Ideally I would just communicate with their service using a simple XHR request and my DSN.
My question is what is the recommended way to track errors that occur before Sentry is initialized in the main JS bundle?

I ended up solving it by adding a barebones window.onerror hook that loads inline before the main bundle arrives. The error is immediately sent to our API and then to our Slack #alerts channel. I added rate limiting so people dont abuse it (too much).
index.html (generated by vue-cli except for the new script tag):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
/>
<title>App title</title>
</head>
<body>
<script>
// This gives us basic error tracking until the main app bundle loads and
// initializes Sentry. Allows us to catch errors that would surface before
// Sentry has a chance to catch them like Edge's `TextEncoder is not defined`.
(function() {
function sendBasicClientError(message, error) {
var xhr = new XMLHttpRequest();
var domain =
window.location.hostname === 'localhost'
? 'http://localhost:5000'
: 'https://example.com';
xhr.open('POST', domain + '/api/v1/basic_client_errors');
xhr.setRequestHeader(
'Content-Type',
'application/vnd.api+json; charset=utf-8'
);
xhr.send(
JSON.stringify({
data: {
type: 'basic_client_error',
attributes: {
error_message: 'Init error: ' + message + ' ' + navigator.userAgent,
error: error
? JSON.parse(
JSON.stringify(error, Object.getOwnPropertyNames(error))
)
: null,
},
},
})
);
}
window.onerror = function(message, filename, lineno, colno, error) {
sendBasicClientError(
message + ' ' + filename + ':' + lineno + ':' + colno,
error
);
};
})();
</script>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
Right before Sentry loads we clear the hook:
// Clears the simple `window.onerror` from `index.html` so that Sentry can
// take over now that it's ready.
window.onerror = () => {};
init({
dsn: 'redacted',
environment,
debug,
integrations: [new VueIntegration({ Vue, logErrors: debug })],
});
Rails controller:
module Api
module V1
class BasicClientErrorsController < ApplicationController
def create
# Can comment out if not using the `pundit` gem.
skip_authorization
# We use `sidekiq` and `slack-ruby-client` gems here.
# Substitute whatever internal error tracking tool you use.
SlackNotifierWorker.perform_async(
basic_client_error_params[:error_message],
'#alerts'
)
head :accepted
end
private
def basic_client_error_params
# We use the `restful-jsonapi` gem to parse the JSON:API format.
restify_param(:basic_client_error).require(:basic_client_error).permit(
:error_message
)
end
end
end
end
Rate limiting with the rack-attack gem:
Rack::Attack.throttle('limit public basic client errors endpoint', limit: 1, period: 60.seconds.to_i) do |req|
req.ip if req.path.end_with?('/basic_client_errors') && req.post?
end

Have you tried this Laxy loading Sentry ?
It's mentioned here that if you set data-lazy to no, or use forceLoad, it'll try to fetch Sentry SDK as soon as possible.
This issue should be handled by the loader, as mentioned here :
Current limitations
Because we inject our SDK asynchronously, we will only monitor global errors and unhandled promise for you until the SDK is fully loaded. That means that we might miss breadcrumbs during the download.
For example, a user clicking on a button on your website is making an XHR request. We will not miss any errors, only breadcrumbs and only up until the SDK is fully loaded. You can reduce this time by manually calling forceLoad or set data-lazy="no".

Related

GWT Bootstrap3 Openlayers offline

I am using GWT with Bootstrap3 and Openlayers Map. I have implemented my own OSM Map server.
My application does not start without internet connection. I need guidance.
I followed the instructions in boostrap3 V1.0.2 for offline applications.
However I only got a blank screen.
Starting with the Firefox debugger I got the following message in the console:
Uncaught ReferenceError: OpenLayers is not defined
<anonymous> http://www.openstreetmap.org/openlayers/OpenStreetMap.js:7
Starting with Google Chrome I get the following warning
[Deprecation] Application Cache API manifest selection is deprecated and will be removed in M85, around August 2020. See https://www.chromestatus.com/features/6192449487634432 for more details.
followed by
GET http://www.openlayers.org/api/OpenLayers.js net::ERR_INTERNET_DISCONNECTED
and
localhost/:1 Application Cache Error event: Invalid or missing manifest origin trial token: http://localhost:8090/simaso/simasoweb/appcache.manifest
Here is my basic setup
SiMaSoWeb.gwt.xml:
...
<inherits name='com.google.gwt.json.JSON'/>
<inherits name="com.google.web.bindery.autobean.AutoBean"/>
<inherits name="org.gwtbootstrap3.extras.cachemanifest.Offline"/>
...
<add-linker name="offline" />
SiMaSoWeb.html:
<!doctype html>
<html manifest="simasoweb/appcache.manifest">
<head>
<title>Sirene</title>
<script type="text/javascript" language="javascript" src="simasoweb/simasoweb.nocache.js"></script>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<link type="text/css" rel="stylesheet" href="SiMaSoWeb.css">
....
</html>
In ...\simasoweb\appcache.manifest I find:
CACHE MANIFEST
# Version: 1599380329409.0.6297069797290025
CACHE:
AF4477772D0DB53A10ABCF74A5AE0C4D.cache.js
fonts/fontawesome-webfont.woff
clear.cache.gif
fonts/FontAwesome.otf
css/bootstrap-notify-custom.min.cache.css
7192594CA2F468C2F793523022719FA0.cache.js
...
css/font-awesome-4.7.0.min.cache.css
NETWORK:
*
Finally
I compile all this . Resources seem to be included in the war file ..
Needless to say that with internet connection, only in the first 1-2 seconds of starting, all is running fine ..
As per the Google Chrome warning you included, App Cache is a deprecated standard and is being removed. It has already been removed from non-secure contexts.
You should be using Service Workers instead to cache resources for offline use. You may have to write your own linker or maybe you can use gwt-serviceworker-linker.
Thanks to ELEVATE I managed to move from AppCache to ServiceWorker. However the Openlayers couldnt be fixed this way. So here is what solved the issues:
ServiceWorker
I am still using Java 8
I upgraded to GWT 2.9
I added to .gwt.xml
<inherits name="org.realityforge.gwt.serviceworker.Linker"/>
<inherits name="elemental2.dom.Dom"/>
<inherits name="elemental2.promise.Promise"/>
<inherits name="jsinterop.base.Base"/>
...
and
<add-linker name="serviceworker"/>
<extend-configuration-property name="serviceworker_static_files" value="./"/>
<extend-configuration-property name="serviceworker_static_files" value="../SiMaSoWeb.html"/>
In my entry JAVA-routine right at the start of my onModuleLod I added
import static elemental2.dom.DomGlobal.*;
import elemental2.dom.DomGlobal;
public void onModuleLoad() {
...
initStatic();
...
and later in that module
public void initStatic() {
if ( null != navigator.serviceWorker )
{
navigator.serviceWorker.register("simasoweb/"+ GWT.getModuleName() + "-sw.js" ).then( registration -> {
console.log( "ServiceWorker registration successful with scope: " + registration.getScope() );
// Every minute attempt to update the serviceWorker. If it does update
// then the "controllerchange" event will fire.
DomGlobal.setInterval( v -> registration.update(), 60000 );
return null;
}, error -> {
console.log( "ServiceWorker registration failed: ", error );
return null;
} );
navigator.serviceWorker.addEventListener( "controllerchange", e -> {
// This fires when the service worker controlling this page
// changes, eg a new worker has skipped waiting and become
// the new active worker.
console.log( "ServiceWorker updated ", e );
} );
}
}
}
I had issues with accesing the right files in my gwt - war directory. Therefore I updated the navigator.serviceWorker.register... command.
Very useful was the google inherent debugger with CTRL+SHIFT+I. In the 'console'-tab you find the messages - red means bad - solve it!
As external jar libraries I had to include
elemental2-core
elemental2-dom
elemental2-promise
base
Now the openlayers issues... Needless to say that there might be a much more elegant way and further more, you need an offline-map, which I have rendered myself and available (150GB for Germany!).
In the HTML file
Note that I opened the openlayers and openstreetmap .js files in a browser copied them in a file and copied them into my war directory in the subdirectory src. Again the browser debugger can help find directory issues.
<script type="text/javascript" language="javascript" src="simasoweb/simasoweb.nocache.js"></script>
<script src="src/OpenLayers.js"></script>
<script src="src/OpenStreetMap.js"></script>
Copy hard
I downloaded the gwt-openlayers demo project GWT-OpenLayers-master.zip
and copied all files in GWT-OpenLayers-master\gwt-openlayers-showcase\src\main\resources\org\gwtopenmaps\demo\openlayers\public\openlayers into my ...war\src\ directory where my openlayers.js files lie.
Finally I am not sure if the service-worker point 1-3 really helped.

Unable to use "Letters" from "CKeditor"

I'm trying to use Letters as the main collaborative text editor for one of our projects. But, I'm unable to run even a simple demo.
This is my "index.html" test page:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="letters.js"></script>
<meta charset="UTF-8">
<script type="text/javascript">
function load() {
Letters.create( document.body, {
cloudServices: {
tokenUrl: '<Development token URL from https://dashboard.ckeditor.com>',
uploadUrl: '<Upload URL from https://dashboard.ckeditor.com>',
documentId: 'cats'
},
title: 'Cats',
body: `<p>Cats are awesome.</p>`
} )
.then( letters => {
console.log( letters.getTitle() );
console.log( letters.getBody() );
});
}
</script>
</head>
<body onload="load()">
</body>
</html>
There's also a "letters.js" file, but I couldn't even find a download link for Letters. I had to look at the demo page source to find it. If anyone knows an official link, please tell me.
When I open this file (locally or within a web server), nothing happens. The console shows this messages:
Logging on browser console. See `cloudServices._logUrl` configuration. Object { message: "letters-restarteditor: Restart.", level: "error", stackTrace: "value#file:///home/(...)/letters.js:1:1018463\n", data: {...} } letters.js:1:47910
Logging on browser console. See `cloudServices._logUrl` configuration. Object { message: "letters-restarteditor: Restart.", level: "error", stackTrace: "value#file:///home/(...)/letters.js:1:1018463\n", data: {...} } letters.js:1:47910
Logging on browser console. See `cloudServices._logUrl` configuration. Object { message: "letters-restarteditor: Switched to offline mode. Too many restarts.", level: "error", stackTrace: "value#file:///home/(...)/letters.js:1:1018463\n", data: {...} } letters.js:1:47910
Does anyone knows what can be happening? Is "Letters" a stable and reliable tool to use in a big project? Being built over CKEditor5, is CKEditor5 a stable and reliable tool? Or I should better stick with CKEditor4?
Thanks in advance!
There has been no official release of Letters so far, that's why tere is no download link for it. The documentation was published for people who are trying Letters in a private beta program.
I have a good news though, next week there will be a free trial officially available with valid download links, updated documentation, which should work just fine. Within the next few days after offering the trial we will also document on how to customize Letters, add/remove plugins and so on.
As of the end of April 2018, you can sign up to Letters and try it out. For the quick start guide check https://docs.ckeditor.com/letters/latest/guides/integration/quick-start.html

How to run SystemJs module when view loads

I have a component that loads a javascript module that builds on Bootstrap.js and Jquery to automatically build a table of contents for a page based on H1,H2,... headers. The component code is as follows:
import { bindable, bindingMode, customElement, noView } from 'aurelia-framework';
#noView()
#customElement('scriptinjector')
export class ScriptInjector {
#bindable public url;
#bindable public isLocal;
#bindable public isAsync;
#bindable({ defaultBindingMode: bindingMode.oneWay }) protected scripttag;
private tagId = 'bootTOCscript';
public attached() {
if (this.url) {
this.scripttag = document.createElement('script');
if (this.isAsync) {
this.scripttag.async = true;
}
if (this.isLocal) {
System.import(this.url);
return;
} else {
this.scripttag.setAttribute('src', this.url);
}
document.body.appendChild(this.scripttag);
}
}
public detached() {
if (this.scripttag) {
this.scripttag.remove();
}
}
}
Essentially for those not familiar with Aurelia, this simply uses SystemJs to load the bootstrap-toc.js module from my app-bundle wherever I put this on my view:
<scriptinjector url="lib/bootstrap-toc.js" is-local.bind='true'></scriptinjector>
My problem is that although this works perfectly when I first load the view, subsequent visits don't generate a TOC (table of contents). I have checked that Aurelia is in fact calling System.Import each time the view is loaded, but it seems that once a module has been imported once, it is never imported again (the code from the bundle never runs a second time).
Does anyone know how I can unload/reload/reset/rerun the module when I re-enter the view?
Ok, so after days of fighting with this I have figured out an acceptable solution that keeps all the functionality of the TOC library and requires as few changes to the skeleton project and the target library as I could manage. Forget the script injector above.
In the index.html, do as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Holdings Manager</title>
<!--The FontAwesome version is locked at 4.6.3 in the package.json file to keep this from breaking.-->
<link rel="stylesheet" href="jspm_packages/npm/font-awesome#4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" href="styles/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app="main" data-spy="scroll" data-target="#toc">
<div class="splash">
<div class="message">Holdings Manager</div>
<i class="fa fa-spinner fa-spin"></i>
</div>
<!-- The bluebird version is locked at 4.6.3 in the package.json file to keep this from breaking -->
<!-- We include bluebird to bypass Edge's very slow Native Promise implementation. The Edge team -->
<!-- has fixed the issues with their implementation with these fixes being distributed with the -->
<!-- Windows 10 Anniversary Update on 2 August 2016. Once that update has pushed out, you may -->
<!-- consider removing bluebird from your project and simply using native promises if you do -->
<!-- not need to support Internet Explorer. -->
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script src="jspm_packages/npm/bluebird#3.4.1/js/browser/bluebird.min.js"></script>
<script src="jspm_packages/npm/jquery#2.2.4/dist/jquery.min.js"></script>
<script src="jspm_packages/github/twbs/bootstrap#3.3.7/js/bootstrap.min.js"></script>
<script>
System.import('core-js').then(function() {
return System.import('polymer/mutationobservers');
}).then(function() {
System.import('aurelia-bootstrapper');
}).then(function() {
System.import('lib/bootstrap-toc.js');
});
</script>
</body>
</html>
This is assuming you have installed bootstrap using jspm (which brings in jquery as a dependency). This also assumes you have put the javascript library (the one you want to incorporate, bootstrap-toc in my case) in your src/lib folder and that you have configured your bundling to include js files from your source folder.
Next, if your library has a self executing anonymous function defined, you need to take that code and move it inside the 'attached' method of the viewmodel where you want the library to be applied. So in this case, I have a 'help' view with a bunch of sections/subsections that I wanted a TOC generated for, so the code looks like:
import { singleton } from 'aurelia-framework';
#singleton()
export class Help {
public attached() {
$('nav[data-toggle="toc"]').each((i, el) => {
const $nav = $(el);
window.Toc.init($nav);
});
}
}
The code inside the 'attached' method above was cut and pasted from the bootstrap-toc.js file and I removed the self-executing anonymous method.
I tried using system.import for the jquery/bootstrap libraries but that made part of the TOC functionality stop working and I have lost my patience to figure out why so those libraries are staying as script references for now.
Also, when you build the project you will get errors :
help.ts(7,7): error TS2304: Cannot find name '$'.
help.ts(9,16): error TS2339: Property 'Toc' does not exist on type 'Window'.
These do not cause problems at runtime since both $ and Toc will be defined before the view is ever instantiated. You can solve these build errors with this solution here.

Ensure phonegap and plugins load before Sencha loader

I have written an application in Sencha Touch 2.1, of which I embed a package build into Cordova/PhoneGap 2.5.0 and compile in xCode to run on iOS Simulator / iOS. I have added the PGSQLite plugin to PhoneGap, and built my own PhoneGap/SQLite Proxy for Sencha, which I used on a few of my Stores.*
Problem: When I embed a package build into PhoneGap and run in iOS Simulator, I see that Cordova does not load before Sencha initializes. I see this because my calls in my Sencha app to Cordova.exec that I make in my Proxy initialization result in an error telling me that the Cordova object cannot be found.
I do successfully use Cordova.exec later in my application to run things like the Childbrowser plugin for PhoneGap, and it works. But using Cordova.exec at an early stage in the app's execution, i.e., initialization, is too soon to guarantee that the Cordova object will have been instantiated.
Already tried: I already tried the following approaches:
I tried simply embedding the developer build of my Sencha app into PhoneGap. Although this worked, I don't want to deploy my development build as my released app because it is inefficient and takes up a lot of space. I have learned from this experiment, however, that the way the Sencha Touch microloader works on package and production builds loads PhoneGap after Sencha. This can be clearly seen when inspecting the DOM after Sencha loads in a package build.
I have already configured my app.json file to include PhoneGap and
my plugins before app.js and the Sencha Touch framework. Playing
with the order of my JS file references in my app.json did not
seem to affect the load order.
I also tried creating a script loader, as described here
(StackOverflow). I then ran the script loader for Cordova, and in
the callback for that, ran the script loader for my plugin, and
then, finally, in the callback for that, ran the Sencha Touch
microloader. This resulted in an error. Additionally, I had to
manually set that up in my index.html file after Sencha built my
package. This seems unacceptable.
What I am looking for: I am looking for answers to the following:
Is there a way to configure Sencha's microloader or my Sencha app in general so that Cordova is ensured to have loaded before Sencha's microloader runs?
Is there a way to set this up so that using Sencha Cmd still works, and I don't have to hack around in my index.html file after I build the app?
Note:
*Please don't suggest I use the existing, so-called, SQLite Proxy for Sencha. I specifically chose my approach because, though I appreciated the existing work on a SQLite proxy for Sencha Touch 2 (namely, this), it is actually a WebSQL proxy that does not store natively in SQLite on iOS. My proxy uses the PGSQLite plugin for PhoneGap to natively store data in SQLite on iOS. I plan to open-source it when I have an opportunity to clean it up and untangle it from my code.
I ended up solving this myself by building a custom loader. I am not sure if there is a more Sencha-ish way to do it, but here are the details of what I did, which does work, in case anyone else wants to ensure that PhoneGap is completely loaded in package and production builds before running anything in Sencha. (That would probably be the case in all scenarios in which PhoneGap is packaging a Sencha app).
My index.html file:
<!DOCTYPE HTML>
<html manifest="" lang="en-US">
<head>
<!-- Load Cordova first. Replace with whatever version you are using -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad() {
// Check for whatever mobile you will run your PhoneGap app
// on. Below is a list of iOS devices. If you have a ton of
// devices, you can probably do this more elegantly.
// The goal here is to only listen to the onDeviceReady event
// to continue the load process on devices. Otherwise you will
// be waiting forever (literally) on Desktops.
if ((navigator.platform == 'iPad') ||
(navigator.platform == 'iPhone') ||
(navigator.platform == 'iPod') ||
(navigator.platform == 'iPhone Simulator') ||
(navigator.platform == 'iPadSimulator')
) {
// Listening for this event to continue the load process ensures
// that Cordova is loaded.
document.addEventListener("deviceready", onDeviceReady, false);
} else {
// If we're on Desktops, just proceed with loading Sencha.
loadScript('loader.js', function() {
console.log('Finished loading scripts.');
});
}
};
// This function is a modified version of the one found on
// StackOverflow, here: http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded#answer-756526
// Using this allows you to wait to load another script by
// putting the call to load it in a callback, which is
// executed only when the script that loadScript is loading has
// been loaded.
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
}
};
head.appendChild(script);
}
function onDeviceReady() {
console.log("[PhoneGap] Device initialized.");
console.log("[PhoneGap] Loading plugins.");
// You can load whatever PhoneGap plugins you want by daisy-chaining
// callbacks together like I did with pgsqlite and Sencha.
loadScript('pgsqlite_plugin.js', function() {
console.log("[Sencha] Adding loader.");
// The last one to load is the custom Sencha loader.
loadScript('loader.js', function() {
console.log('Finished loading scripts.');
});
});
};
</script>
<meta charset="UTF-8">
<title>Sencha App</title>
</head>
<!-- Don't forget to call onBodyLoad() in onLoad -->
<body onLoad="onBodyLoad();">
</body>
</html>
Next, create a custom loader in loader.js in your document root, alongside your index.html. This one is heavily based on the development microloader that comes with Sencha. Much props to them:
console.log("Loader included.");
(function() {
function write(content) {
document.write(content);
}
function meta(name, content) {
write('<meta name="' + name + '" content="' + content + '">');
}
var global = this;
if (typeof Ext === 'undefined') {
var Ext = global.Ext = {};
}
var head = document.getElementsByTagName("head")[0];
var xhr = new XMLHttpRequest();
xhr.open('GET', 'app.json', false);
xhr.send(null);
var options = eval("(" + xhr.responseText + ")"),
scripts = options.js || [],
styleSheets = options.css || [],
i, ln, path;
meta('viewport', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no');
meta('apple-mobile-web-app-capable', 'yes');
meta('apple-touch-fullscreen', 'yes');
console.log("Loading stylesheets");
for (i = 0,ln = styleSheets.length; i < ln; i++) {
path = styleSheets[i];
if (typeof path != 'string') {
path = path.path;
}
var stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
stylesheet.href = path;
head.appendChild(stylesheet);
}
for (i = 0,ln = scripts.length; i < ln; i++) {
path = scripts[i];
if (typeof path != 'string') {
path = path.path;
}
var script = document.createElement("script");
script.src = path;
head.appendChild(script);
}
})();
Notice that your index.html file does not contain a #microloader script element. That's because you should take it out and use your custom loader.
With all that in place, you will be able to sail smoothly, knowing that the whole PhoneGap environment is in place before your Sencha javascript starts doing things.

Dojo - Issue loading widget cross-domain

I'm working on a project that requires that some custom Dojo widgets (i.e., widgets we have written ourselves) are loaded from another server. Despite my best efforts over several days, I cannot seem to get Dojo to load the widgets.
Dojo is loaded from the Google CDN, the widget is loaded from www.example.com, and the website is located at www.foo.com.
I cannot post the actual project files (this is a project for a company), but I have reproduced the error with smaller test files.
Test.html (on www.foo.com):
<html>
<div id="content"></div>
<script>
var djConfig = {
isDebug: true,
modulePaths: {
'com.example': 'http://example.com/some/path/com.example'
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.4.3/dojo/dojo.xd.js.uncompressed.js"></script>
<script type="text/javascript">
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.addOnLoad(function() {
dojo.require("com.example.widget.Test", false);
dojo.addOnLoad(function() {
new com.example.widget.Test().placeAt(dojo.byId('content'));
});
});
</script>
</html>
Test.xd.js (at www.example.com/some/path/com.example/widget/Test.xd.js):
dojo.provide("com.example.widget.Test");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("com.example.widget.Test", [dijit._Widget, dijit._Templated], {
templateString: "<div dojoAttachPoint=\"div\">This is a test</div>",
postCreate: function() {
console.log("In postCreate");
console.log(this.div);
this.div.innerHTML += '!!!';
}
});
In Firebug, I am seeing an error after a delay of a few seconds saying that the cross-domain resource com.example.widget.Test cannot be loaded. However, in the 'Net' tab I am able to see that Test.xd.js is successfully downloaded, and I am able to set a breakpoint and see that the dojo.declare executes and completes without error.
I appreciate any help. Please let me know if there is any other information I can provide.
There is a different way for handling the module declarations in XD-loader. This is due to how the loader handles 'module-ready' event. You will most likely experience, that the dojo.addOnLoad never runs, since it 'knows' that certainly - some required modules are not declared.
Even so, they may very well be declared - and the change in 1.7+ versions of dojotoolkit seem to reckognize that fact. The reason for this, i believe, is that the mechanism for 'module-ready' is not implemented correctly in your myModule.xd.js modules.
It is basically a 'header' or 'closure' of the declaration, involving a few steps - wrapping everything in your basic module from dojo.provide and eof
Standard example boiler module file '{{modulePath}}/my/Tree.js'
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
X-Domain example boiler module file '{{modulePath}}/my/Tree.xd.js
dojo._xdResourceLoaded(function(){
return {
depends: [
["provide", "my.Tree"],
["require", "dijit.Tree"]
],
defineResource: function(dojo) {
///////////////////////////////
/// Begin standard declaration
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
/// End standard declaration
///////////////////////////////
}
}
})();