Best way to execute js only on specific page

前端 未结 4 1857
慢半拍i
慢半拍i 2020-11-28 22:13

I was wondering what would be the best way to execute a java-script code only on specific pages.

Let\'s imagine we have a template-based web-site, rewrite rule for t

相关标签:
4条回答
  • 2020-11-28 22:20

    I would use the switch statement and a variable. (I'm using jQuery!)

    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;
    }
    
    //use windowLoc as necessary elsewhere
    

    This will allow you to change what "button" does based on the page that you're on. If I understood your question correctly; this is what I would do. Also, if I had were serving large amounts of javascript, I would simply add a new JS file completely.

    var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
    
    switch(windowLoc){      
      case "/info.php":
        var infoJS = document.createElement('script');
        infoJS.type = 'text/javascript';
        infoJS.src = 'location/to/my/info_file.js';
        $('body').append(infoJs);
        break;
      case "/alert.php":
        var alertJS = document.createElement('script');
        alertJS.type = 'text/javascript';
        alertJS.src = 'location/to/my/alert_file.js';
        $('body').append(alertJs);
        break;
    }
    

    Hope this helps -

    Cheers.

    0 讨论(0)
  • 2020-11-28 22:23

    You can use Require js (RequireJS is a JavaScript file and module loader) and load script if they only needed. Link is http://requirejs.org/, I know using require js not so much easy.

    0 讨论(0)
  • 2020-11-28 22:28

    A little different approach than checking the URL path : You can group page specific event handlers in a single function and then in each include, have a domready which will call these functions.

    Eg: in script.js you have two functions (outside domready) viz. onPage1Load() and onPage2Load().

    While in your page1.php you have a $(document).ready(onPage1Load) and so on for other pages. This will make sure that unintended event handlers are not registered.

    0 讨论(0)
  • 2020-11-28 22:37

    Set a class attribute to your body tag.

    <body class="PageType">
    

    And then in your script..

    $(function(){
      if($('body').is('.PageType')){
        //add dynamic script tag  using createElement()
        OR
        //call specific functions
      }
    });
    
    0 讨论(0)
提交回复
热议问题