2

I'm working on my first ASP.NET MVC 3 application with utilizes some JavaScript and jQuery here and there. I ran into a problem with a particular jQuery plugin that ended up being referenced multiple times and this resulted in a stackoverflow/too much recursion error when I tried to use the plugin on the page. Moving this out of my partial view file and into the _Layout.cshtml caused the error to go away, but I'm thinking this isn't really the solution either.

I'm still very new to JavaScript and jQuery and was wondering if there's a guard, like I would use in a C file to avoid multiple includes of a particular header file, to do likewise with a JavaScript file.

Or, if there's a better way to handle this, I'd be interested in hearing how. Perhaps it is an issue just with this particular plugin file. Any guidance on this?

2

1 Answer 1

3

I used the code below to solve a similar issue.

function requireOnce(url) {    
if (!$("script[src='" + url + "']").length) {
    $('head').append("<script type='text/javascript' src='" + url + "'></script>"); 
}

}

Credit

Option 2

I just found this thread. I've yet to try it but if you are using razor it sounds like it could be perfect. I'll have to try this myself.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - missed the original question.
It's understandable, most of the results that are returned are for the RegisterClientScript which only works in webforms. Also, I had to go through a few other versions of similar scripts before I found one that works, so hopefully it works for you.
NB: Small typo in the 2nd line where it says scr=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.