Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery.getScript show the file as a resource in Chrome Developer Tools?

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();
}
like image 341
codefactor Avatar asked Aug 17 '15 18:08

codefactor


2 Answers

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.

like image 194
nrabinowitz Avatar answered Oct 22 '22 02:10

nrabinowitz


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:

  1. Set global .ajax caching (not recommended) before you call .getScript():

    $.ajaxSetup({
      cache: true
    });
    
  2. Use direct .ajax() call (recommended):

    $.ajax({
        dataType: "script",
        cache: true,
        url: url
    }
    
  3. 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).

like image 44
Kamil Szymański Avatar answered Oct 22 '22 01:10

Kamil Szymański