当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Razor generates jQuery too late for custom script using it despite Scripts.Render order

问题描述:

I've asked why the below doesn't work and got a very clear answer.

<head>

...

<script src="Stuff.js" type="text/javascript"></script>

</head>

<body>

...

@Scripts.Render("~/bundles/jquery")

</body>

So I've changed that into this.

<head></head>

<body>

@RenderBody()

@Scripts.Render("~/bundles/jquery")

@Scripts.Render("~/Stuff.js")

</body>

However, I get the same misbehavior. Based on the diagnostics from the linked answer, I'm guessing that the scripts still don't render in the right order. How do I control it? Should I move both to header instead?

The generated markup ends like this.

 </form>

</div>

<script src="/Scripts/jquery-1.10.2.js"></script>

<script src="Stuff.js"></script>

</body>

</html>

As asked - I'm adding a screenshot of the network tab showing scripts. There are other resources as well (images and stuff) but none of them is 4xx, no weird messages and I've turned them each off, still hitting the same problem.

Working in Default.js (formerly Stuff.js).

window.onload = function() {

console.log($(this));

};

Producing error in Default.js (any of the lines).

//$(document).ready(function () { alert("ready"); });

$(window).onload(function () { alert("onload"); });

网友答案:

You should use

$(window).load(function () { alert("onload"); });

onload is JavaScript native event, but in JQuery is load

Please refer to the following post for more details : difference between $(window).load(function() { and $(document).ready(function() {

The second point and most importantly is you have the following

 @RenderBody()
 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/Stuff.js")

If there any JQuery call in your views, let say you needed to call something in your home page, then JQuery library is not defined yet. Because Jquery renders after RenderBody

What you need to do is put a Section and and render the section after Jquery is loaded

You should have the following in your layout

@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Stuff.js")
@RenderSection("Scripts", required: false) 

And in your views put the javascripts calls in the section

@section Scripts {
<script type="text/javascript">
        //<![CDATA[
        $(document).ready(function() { alert ('Hi'); });
        //]]>
</script>
}

I hope this helps

分享给朋友:
您可能感兴趣的文章:
随机阅读: