1

I would like to use a very strict Content Security Policy which does not allow inline Javascript. My views are rendered with php. All my Javascript Logic needed throughout the application is already external concatenated in one Javascript file app.js. Only the page specific initialization logic is inline in the php views, e.g.:

<script>
jQuery(document).ready(function(){
        cebIntranet.home.init();
});
</script>

Now my question is how to also externalize the inline Javascript initialization logic. I could think of the following approaches but I am not happy with them. Is there a better solution? Which are the recommended best practices?

  1. Create a separate Javascript file for each page which does only hold the initialization logic => I do not like the idea to request an additional file which has at least only one line in it.
  2. Move the initialization logic also into the app.js file and make them dependent from the body id or class. => I do not like the idea to have a big if statement which chooses the right initialization logic dependent on a body class or id.
griesi
  • 370
  • 3
  • 12

1 Answers1

1

Create a class which have array variable and two member functions i.e. addJs & writeJs with below argument

  1. Addjs Arguments
    • $jsstring => Javascript Code / filename, which add the string into array variable.
    • $type => like 1) inline => which write inline code. 2) file => which takes the code from file.
  2. writeJs => No arguments required.

Create an globally accessible object for a class and use the addJS instead of writing script directly into file.

You need to use writeJs function to write the code into file when displaying html on browser whatever scripts added into array variable.

It should work for you.