Specific JavaScript page using Content Security Policy (CSP)

I want to use Content Security Policy (CSP) throughout my site. This requires all JavaScript to be in separate files. I used the general JavaScript used by all pages, but there is also JavaScript for specific pages that I want to use only for a specific page. What is the best way to handle JavaScript for JavaScript for better performance?

Two ways I can come up with to solve this problem are to use special JavaScript packages or a separate JavaScript package with a switch statement to execute the contents of the page.

+6
source share
2 answers

There are many ways to execute page specific javascript

Option 1 (check through the class)

Set body to body tag

<body class="PageClass">

and then check through jQuery

$(function(){
  if($('body').hasClass('PageClass')){
    //your code
  }
});

Option 2 (check through the switch enclosure)

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname

switch (windowLoc) {
    case "/info.php":
        //code here
        break;
    case "/alert.php":
        //code here
        break;
}

Option 3 Check via function

make whole page script in function

function homepage() {
    alert('homepage code executed');
}

and then run the function on a specific page

homepage();
+1
source

Sorry, I know that this ended up being read for a long time, but it will be worth it to do this, as you can make the choice that suits your site. For tl; dr, read the first sentence of each paragraph.

, , , JS, , . . , , minifier, , - . , - Google - , .

JS- , ( ) "", ( ) "". , , . , , JS ( , , 10 , ). , JS , , JS, , . , async defer, .

, A 5 JS, B - 5 JS. , A ( ~ 5 JS), B - , JS. , A , B, . JS, , . , "" ( , ).

, JS , , . JS , ( , ), , . . , , JS, , ( ), JS , .

!. , , async defer script, "JS.

async JS. JS , " , ". , JS , ( , async defer).

js , , ( ) js, script, async defer ( " " ). defer , .

, , . , , / . , , .

+2

Source: https://habr.com/ru/post/1016786/


All Articles