如何在浏览器的调试器中调试动态加载的 JavaScript (使用 jQuery) ?

在浏览器的调试器脚本部分中没有显示动态添加的脚本。

说明:

我需要使用和已经使用

if( someCondition == true ){
$.getScript("myScirpt.js", function() {
alert('Load Complete');
myFunction();
});
}

以便在满足某些条件时可以动态加载 myScript.js..。 只有在加载了整个脚本之后才能调用 myFunction..。

但是浏览器没有在调试器的脚本部分显示动态加载的 myScript.js。

是否有其他的方法可以实现所有的目标,使一个人能够调试一个动态加载的脚本在浏览器本身?

49037 次浏览

You can give your dynamically loaded script a name so that it shows in the Chrome/Firefox JavaScript debugger. To do this you place a comment at the end of the script:

//# sourceURL=filename.js

This file will then show in the "Sources" tab as filename.js. In my experience you can use 's in the name but I get odd behaviour if using /'s.

Since if a domain it is not specified filename.js will appear in a folder called "(no domain)" it is convenient to specify a domain for improving the debugging experience, as an example to see a "custom" folder it is possible to use:

//# sourceURL=browsertools://custom/filename.js

A complete example follows:

window.helloWorld = function helloWorld()
{
console.log('Hello World!');
}
//# sourceURL=browsertools://custom/helloWorld.js

For more information see: Breakpoints in Dynamic JavaScript deprecation of //@sourceurl

I tried using the "//# sourceURL=filename.js" that was suggested as a workaround by the OP, but it still wasn't showing up for me in the Sources panel unless it already existed in my tabs from a previous time when it produced an exception.

Coding a "debugger;" line forced it to break at that location. Then once it was in my tabs in the Sources panel, I could set breakpoints like normal and remove the "debugger;" line.

Notice that the source file appearing in the sources tab this way will appear in the (no domain) group and, in case you want to debug it, you will need to add a debugger; line in your code, make that line be executed (usually at the start of the execution of your source file) and then add your breakpoints wherever you want.

In case you are debugging production stages, where you will probably have no debugger; lines in your code, you can make this happen by doing a local map with CharlesProxy to your "fresh copy of the source file with the debbuger line inserted".

You can use //# sourceURL= and //# sourceMappingURL= at the end of your script file or script tag.

NOTE: //@ sourceURL and //@ sourceMappingURL are deprecated.

When trying to track this sort of thing down in IE, I open the dev tools (F12) and then find where to place the breakpoint by using the following line in the console:

debugger;myFunction();

That switches to the debugger tab where you can step into myFunction() and set the breakpoint.