Keeping jQuery code away from html files

I am learning jQuery and creating some plugins. Unfortunately, due to the practice of my coding company, they want all javascript codes to be extracted from js files. This creates two problems for me:

  • Is it possible to extract the actual call to $ (document) .ready (..) in a js file? Until now, with my limited knowledge, I have not thought how much this is possible. If not, I welcome any suggestions to make this a cleaner and more acceptable way to include this code.
  • There is too much javascript for each asp.net header, since I can use multiple plugins. Is there a way to reduce the potential costly server trips that I will need to do every time I need these files?

Any suggestions, corrections are welcome.

thanks

+3
source share
5 answers

1. Absolutely.

Just add a script link to your html like this:

<script type='text/javascript' src='js/yourfile.js'></script> 

Then just run your .js file with

jQuery(function() {
  foo;
  ...
  bar;
});

or any other shortcuts to run the jQuery code block.

2.Before sending it to the user, you must run your scripts using Minify . This will combine the files and pack them nicely so that they take up less space.

+8
source

Using $ (document) .ready () in an external javascript file is fine - it will work the same way :) Actually - it will not only work, but it is good practice, as it helps to separate content (HTML) from behavior (Javascript )

javascript , <head> . -, , .

jQuery, ​​:

<html>
  <head>
    <!-- html tags such as title, link, meta etc -->
    <script type="text/javascript" src="/path/to/jquery.js"></script>
    <script type="text/javascript" src="/path/to/plugin.js"></script>
    <!-- more plugins included if required -->
  </head>
  <body>
    <!-- html here -->

    <!-- script is the last thing before the ending body tag (increases performance) -->
    <script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
  </body>
</html>
+2

, javascript . , ? javascript.

, ,

- jquery
-write .net, (, )

js .

+1

document.ready JavaScript .

2 - jQuery global.js, .

front end blender, .

+1

, document.ready . , , , js html. , ,

var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
    //do something for this page only
}

.

+1

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


All Articles