简体   繁体   中英

Debug a script that sits in a partial view

Why I can't debug scripts that reside in a partial view, that gets created in runtime? To see the script in the list of scripts (in Chrome for example) and debug it, I have to move it to the "regular" view on the upper level or I have to move it to a separate .js file. But what, if the script so small that I don't want to move it anywhere, and still want to be able to debug it?

If you do not load the partial view via ajax (the view is in place at the initial page rendering) you can use 'debugger'. If the code you want to run is added to the dom IE will not know where the actual code is located that you want to debug. So:

// javascript
var foo = 2;
debugger;
// more javascript

There's a much better way to do this now, just use the syntax

//@@ sourceURL=someValue

immediately after opening your script tag. Example:

<script type="text/javascript">
    //@@ sourceURL=_fooPartialView.cshtml
    function foo() {}
</script>

--edit--

Apparently due to some IE compatibility issue javascript source mapping has been changed from the above to:

//# sourceURL=_fooPartialView.cshtml

Also note, although not mentioned earlier, the @@ was only necessary for source mapping in razor views since "@" had other significance.

It's generally considered poor practice to include a script inside of a partial view. You could run into all kinds of issues with multiple script references and performance. The better approach here is to ensure the script gets moved up to a placeholder in your head tag. For a few examples on this, check out:

Linking JavaScript Libraries in User Controls

and

Include JavaScript file in partial views

If you insist on loading the script from the partial, the 'debugger' approach above is very effective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM