I’m stuck on a JavaScript problem. I want to load an external JS file from inside a function. The file loads fine (I tested with an alert), but I can’t figure out how to get data back from it and put it in an array.
Here’s what I’m trying to do:
$(document).ready(function() {
function importExternalScript(scriptPath) {
let scriptElement = document.createElement('script');
scriptElement.src = scriptPath;
scriptElement.type = 'text/javascript';
scriptElement.async = true;
scriptElement.onload = () => console.log(`${scriptPath} loaded OK`);
scriptElement.onerror = () => console.error(`Failed to load ${scriptPath}`);
document.head.appendChild(scriptElement);
}
let teamData = importExternalScript('teamInfo.js');
});
// teamInfo.js content:
let squads = [];
for (let i = 0; i < 4; i++) {
squads.push({ name: `Squad ${i + 1}` });
}
// How do I return squads to the main script?
The files are in the same folder. I want to use this with a resume event later. If the array has data, do nothing; otherwise, run the script. Any ideas on how to return and use the data from the external file?
hey there hazel! i’ve run into this before. the problem is that script loading is asynchronous—you can’t return data directly from importExternalScript. instead, use a callback function:
function importExternalScript(scriptPath, callback) {
// ... your existing code ...
scriptElement.onload = () => {
console.log(`${scriptPath} loaded OK`);
callback(squads); // Call the callback with the data
};
}
importExternalScript('teamInfo.js', (teamData) => {
console.log(teamData); // Use the data here
});
hope this helps!
As someone who’s tackled this problem before, I can tell you that Promises are your friend here. They’re perfect for handling asynchronous operations like script loading. Here’s how I’d approach it:
function importExternalScript(scriptPath) {
return new Promise((resolve, reject) => {
let scriptElement = document.createElement('script');
scriptElement.src = scriptPath;
scriptElement.type = 'text/javascript';
scriptElement.async = true;
scriptElement.onload = () => {
console.log(`${scriptPath} loaded OK`);
resolve(window.squads); // Assume the script sets a global 'squads'
};
scriptElement.onerror = () => reject(`Failed to load ${scriptPath}`);
document.head.appendChild(scriptElement);
});
}
$(document).ready(async function() {
try {
let teamData = await importExternalScript('teamInfo.js');
console.log('Team data loaded:', teamData);
// Use teamData here
} catch (error) {
console.error('Error loading script:', error);
}
});
This approach gives you more control and makes error handling easier. It’s also more in line with modern JavaScript practices. Just make sure your teamInfo.js script sets window.squads instead of a local variable.
I’ve encountered a similar issue before. One approach you could consider is using a global variable to store the data from the external script. In your main script, declare a global variable like ‘window.squads = ;’. Then in teamInfo.js, populate this global variable instead of creating a local one.
Here’s how you might modify your code:
// In your main script
window.squads = [];
function importExternalScript(scriptPath) {
// Your existing code here
}
importExternalScript('teamInfo.js');
// Check if data is loaded
function checkData() {
if (window.squads.length > 0) {
console.log('Data loaded:', window.squads);
} else {
setTimeout(checkData, 100); // Check again in 100ms
}
}
checkData();
This method allows you to access the data globally once it’s loaded, without needing to return it directly from the function.