mirror of
https://github.com/jspsych/jsPsych.git
synced 2025-05-12 16:48:12 +00:00
Merge pull request #948 from bjoluc/fix-duplicate-body
Delay `init()` execution until the document is ready
This commit is contained in:
commit
d621710625
10
jspsych.js
10
jspsych.js
@ -52,7 +52,7 @@ window.jsPsych = (function() {
|
|||||||
//
|
//
|
||||||
|
|
||||||
core.init = function(options) {
|
core.init = function(options) {
|
||||||
|
function init() {
|
||||||
if(typeof options.timeline === 'undefined'){
|
if(typeof options.timeline === 'undefined'){
|
||||||
console.error('No timeline declared in jsPsych.init. Cannot start experiment.')
|
console.error('No timeline declared in jsPsych.init. Cannot start experiment.')
|
||||||
}
|
}
|
||||||
@ -205,6 +205,14 @@ window.jsPsych = (function() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// execute init() when the document is ready
|
||||||
|
if (document.readyState === "complete") {
|
||||||
|
init();
|
||||||
|
} else {
|
||||||
|
window.addEventListener("load", init);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
core.progress = function() {
|
core.progress = function() {
|
||||||
|
|
||||||
var percent_complete = typeof timeline == 'undefined' ? 0 : timeline.percentComplete();
|
var percent_complete = typeof timeline == 'undefined' ? 0 : timeline.percentComplete();
|
||||||
|
48
tests/jsPsych/init.test.js
Normal file
48
tests/jsPsych/init.test.js
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
require("../../jspsych");
|
||||||
|
require("../../plugins/jspsych-html-keyboard-response");
|
||||||
|
|
||||||
|
describe("jsPsych init", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
document.body.innerHTML = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
function setReadyState(targetState) {
|
||||||
|
jest
|
||||||
|
.spyOn(document, "readyState", "get")
|
||||||
|
.mockImplementation(() => targetState);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getBodyHTML() {
|
||||||
|
return document.body.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
jsPsych.init({
|
||||||
|
timeline: [
|
||||||
|
{
|
||||||
|
type: "html-keyboard-response",
|
||||||
|
stimulus: "foo",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it("should delay execution until the document is ready", () => {
|
||||||
|
expect(getBodyHTML()).toBe("");
|
||||||
|
|
||||||
|
setReadyState("loading");
|
||||||
|
init();
|
||||||
|
expect(getBodyHTML()).toBe("");
|
||||||
|
|
||||||
|
// Simulate the document getting ready
|
||||||
|
setReadyState("complete");
|
||||||
|
window.dispatchEvent(new Event("load"));
|
||||||
|
expect(getBodyHTML()).not.toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should execute immediately when the document is ready", () => {
|
||||||
|
// The document is ready by default in jsdom
|
||||||
|
init();
|
||||||
|
expect(getBodyHTML()).not.toBe("");
|
||||||
|
});
|
||||||
|
});
|
Loading…
Reference in New Issue
Block a user