I'm loading this html in JSDOM:
./template.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>title</title>
</head>
<body>
<div>hi</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
console.log(`2nd script: Does window.$ exist?`, window.$ !== undefined && window.$ !== null);
console.log(`2nd script: Does $ exist?`, $ !== undefined && $ !== null);
</script>
</body>
</html>
My question is, how do I know if a resource (e.g., https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js) was successfully loaded? That url is simply an example. I'm asking in general.
Here is the rest of my project structure:
Project Structure
.
├── .eslintrc.json
├── .prettierrc
├── index.js
├── package.json
└── template.html
./index.js
/* eslint-disable no-unused-vars */
import { JSDOM, ResourceLoader } from 'jsdom';
class CustomResourceLoader extends ResourceLoader {
fetch(url, options) {
console.log(`Called with ${url}`);
return super.fetch(url, options); // was the resource loaded correctly?
}
}
const dom = await JSDOM.fromFile(`./template.html`, {
url: 'http://localhost',
runScripts: 'dangerously',
resources: new CustomResourceLoader(),
pretendToBeVisual: true,
});
const window = dom.window;
const $1 = window.eval('window.$');
console.log(
`jsdom module: Does window.$ exist?`,
$1 !== undefined && $1 !== null
);
./package.json
{
"name": "jsdom-sandbox",
"version": "0.0.1",
"description": "A simple sandbox for playing around with jsdom.",
"main": "index.js",
"type": "module",
"scripts": {
"test": "npm run exec && jasmine",
"exec": "node index.js"
},
"devDependencies": {
"@types/jasmine": "^5.1.1",
"@types/jquery": "^3.5.25",
"@types/jsdom": "^21.1.4",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jasmine": "^5.1.0"
},
"dependencies": {
"@prettier/sync": "^0.3.0",
"jsdom": "^22.1.0",
"prettier": "^3.0.3"
}
}