Farshid Farshid - 1 year ago 57
jQuery Question

Load js file into partial view

I have a layout and a view and a partial view. I used my layout in view and in view I load partial view with ajax into view. I used

@RenderSection("Script", required: false)
in my layout for loading my validation js file into partial view with this statement:

@section Script{
<script src="~/Content/js/register.js"></script>

but after running my project and get view source I saw that file still doesn't load to this page.Then I put
@section Script{ <script src="~/Content/js/register.js"></script> }
in my View in this way file loaded but any of validation don't run. But when I copy script file code into partial view they are running. Now I want know why when I used file don't run my scripts?


Answer Source

You can refer following code to render your script:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
    } else {  //Others
        script.onload = function(){

    script.src = url;

In your case you have to use this function like this:

After your success request:

loadScript("~/Content/js/register.js", function(){
    //initialization code

Hopefully it resolves your issue.


Happy coding :)