Best Practice - Inline javascript with AJAX calls?

I have a project that requires a lot of AJAX calls to pull in content for popovers. I know that it’s not a good idea to have inline javascript according to best practices but in this case, doesn’t it make more sense? I don’t want to have a huge javascript library for all the various things I’m pulling into a modal box or whatever. According to best practice in this respect, is it okay to put javascript at the end of the content I AJAX in or should I call the page and have the page also load a javascript file? Seems like the best and easiest solution would be to put it at the end of the content being pulled in. Then it’s removed from memory as well after closing.

The easiest solution is not always the best. Consider later on when you have to go back and make changes to the JavaScript code. You should not have to open up the HTML code as well in order to make those changes.

Keep your script in a separate file and refer to it from the page. It’s not hard.

<body>
    ...
    <script src="js/someScript.js"></script>
</body>
</html>

Yes, but if I have a full page and then call an ajax page that just has a snippet of html (no body tags or anything) are you saying that you should use the script tag and load in the javascript for that?

While I could understand doing that, it doesn’t remove the javascript from memory when loading something else via ajax to replace the modal window so it’s adding to the memory…and great effort would need to be taken to ensure that the same function names are not used.

Since this website will be more of an application, this is definitely a concern but since it’ll be distributed for others to use, I want to make sure that it’s done correctly.

So that we’re not working at cross purposes here, can you please provide an example of what you mean when you are calling an ajax page?

Yes, so I’ll have a page that will allow me to add various widgets on the page. There are a bunch of different types of widgets and when adding or editing them, it’ll bring up a modal window that will allow the user to edit the widget. When it calls the modal, it will have just the code necessary to edit it not a full html page with body tags, etc. Just the html needed for the modal.

With users opening and editing various widgets over and over, I want to make it as efficient as possible. Hope that helps.

The best practice even in this situation is to have your scripting code in a separate file.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.