To load external JavaScript or CSS files dynamically with jQuery, you can use the $.getScript()
function for JavaScript files and the $.get()
function for CSS files. Here's an example:
// Function to load a JavaScript file dynamically
function loadScript(url) {
return new Promise(function(resolve, reject) {
$.getScript(url)
.done(resolve)
.fail(reject);
});
}
// Usage
loadScript('external_script.js')
.then(function() {
// Script loaded successfully
// You can now use the functions and variables defined in the external_script.js file
})
.catch(function() {
// Script failed to load
});
// Function to load a CSS file dynamically
function loadCSS(url) {
return new Promise(function(resolve, reject) {
$.get(url, function(data) {
$('<style>').html(data).appendTo('head');
resolve();
}).fail(reject);
});
}
// Usage
loadCSS('external_style.css')
.then(function() {
// CSS file loaded successfully
// Styles defined in the external_style.css file are now applied to the document
})
.catch(function() {
// CSS file failed to load
});
Note: In the above examples, Promises are used to handle the asynchronous loading of files and to provide success and error callbacks.