My code needs to load scripts on demand.
function includeJS(uri) {
return jQuery.getScript(uri);
}
includeJS('/path/to/script.js').always(function() {
// do something after script is loaded
});
The problem, though, is that the JS file will not be available in the Chrome Developer tools like other files that were included statically on the page. Due to this I cannot easily put break points.
Is there an alternative to jQuery.getScript that will also show the script in the Chrome Developer tools with the ability to put break points?
EDIT: Adding solution based on currently accepted answer (I will still consider other solutions, but this seems to work for me)
function includeJS(uri) {
var def = $.Deferred();
var script = document.createElement('script');
script.src = uri;
script.onload = function() {
def.resolve();
}
script.onerror = function() {
def.reject();
}
document.body.appendChild(script);
return def.promise();
}
You can simply append a script
tag, and use an onload
handler to execute post-load actions. Example: https://jsfiddle.net/0nu2dusu/
var script = document.createElement('script');
script.src = 'my_external_script.js';
script.onload = loadHandler;
document.body.appendChild(script);
You have slightly less control over failed loads than $.getScript
offers, but the script does show up in dev tools.
Actually it's always there. Just take a look at an example from the jQuery.getScript() site. Here's how it looks like: http://i.imgur.com/LMFFAag.png.
The problem with .getScript()
is that it never caches files requested, so on every call it adds some random string to prevent caching (what also prevents us from debugging code). But there's workaround for that:
Set global .ajax
caching (not recommended) before you call .getScript()
:
$.ajaxSetup({
cache: true
});
Use direct .ajax()
call (recommended):
$.ajax({
dataType: "script",
cache: true,
url: url
}
If it's your own script, you can always add a debugger;
command anywhere to force browser to enter the debug mode (DevTools must be opened).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With