简体   繁体   中英

Combining multiple jquery files

For some reason I can't combine my javascript files in one single file through php, like I can with css.

Basicly I wish to combine all of my javascript files into one. However that breaks my code somehow. It's like the $-value which jQuery generates isn't available through the rest of the code (such as jquery ui).

Does the jQuery need to be loaded in it's own <script type="text/javascript" src=""></script> for some reason? And what is that reason then?

I include them in the same order that they work in the browser.

jQuery -> jQuery UI -> jQuery custom functions -> my own script

You might want to put a new-line and/or semicolon between the single scripts.
Eg the minified jquery ui script you get from https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js ends with

return this}})}(jQuery)

If you now append another script right behind that you will most likely get a syntax error.
Lets take a crude scripts.php

<?php
header('Content-type: Application/javascript');
readfile('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
readfile('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js');

echo '$(document).ready(function() {
    alert("hello");
    $( "#dialog" ).dialog( "open" );
});
';

this won't work, but

<?php
header('Content-type: Application/javascript');
readfile('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
echo "\r\n;";
readfile('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js');
echo "\r\n;";    
echo '$(document).ready(function() {
    alert("hello");
    $( "#dialog" ).dialog( "open" );
});
';

will.

Other things to consider:

  • this is probably not a silver bullet. I chose "\\r\\n;" to a) escape from a // comment in the last line and b) to close an "open" statement with the semi-colon. But the missing-semicolon behaviour of javascript (and the implementations of it) can be rather odd (it's a bad feature) and I'd rather "fix" each individual script manually than adding a fixed "repair string".
  • I'm stronlgy in the "let a cdn like google host those javascript libraries and rely on the client's cache" camp ...but without good evidence at hand to support that position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM