Combines the contents of two or more specified JavaScript objects. The result of the union is written to the first of these objects (it will also be returned by the function after its execution). The function has two uses:

combines the contents of objects target, object1,.., objectN, putting the result into an object target.

Features of use

If you specify two or more objects, the result will be their union. In case you specify only one object, the extend() function will add its contents to global object$(jQuery). In this way, you can extend the capabilities of the library by adding your own functions to its namespace. This can be useful when writing plugins.

Let us recall that as a result of merging objects, the first of them will be changed (it will also be returned as the result of the extend() function). If you want none of the specified objects to be changed, you can set as a parameter target empty object:

var object = $.extend (( ) , object1, object2) ;

Recursive (deep) copying

When merging objects, matching fields are overwritten:

var object1 = (apple: 0, cherry: 97); var object2 = (apple: 5, durian: 100); $.extend(object1, object2) ; /* The result will be as follows: ( apple:5, cherry:97, durian:100 ); */

By default, extend() performs a shallow union of objects, meaning that if they contain other objects inside them, extend() will overwrite them as in the previous case:

var object1 = (apple: 0, banana: (weight: 52, price: 100), cherry: 97); var object2 = ( banana: ( price: 200 ) , durian: 100 ) ; $.extend(object1, object2) ; /* Result: ( apple:0, banana:(price:200), durian:100, cherry:97, ); */

however, if you specify true as the first parameter, then a deep copy will be performed, in which the merging procedure will be applied to the internal objects (rather than rewriting as in the previous case):

var object1 = (apple: 0, banana: (weight: 52, price: 100), cherry: 97); var object2 = ( banana: ( price: 200 ) , durian: 100 ) ; $.extend(true, object1, object2); /* Result: ( apple:0, banana:(weight:52, price:200), durian:100, cherry:97, ); */

This action reduces the number of requests to the server, thus speeding up the site. This is especially true for HTTP1.1 and pages that require more than 20 requests. In addition, this adds points in the test (which for many is the most important thing).

How to Combine Javascript Files in WordPress into One File - The No-Plugin Method

In general, there are plugins for this task, but in the comments to those plugins there are a lot of reviews in the spirit of “it doesn’t work.”

If you do it “completely manually”, then you will have to take all the piles of code manually and copy them into one file. This method is not recommended as it has many disadvantages such as:

1.) It is difficult to find the javascript file descriptor name, this is in contrast to CSS files where we can find the id attribute descriptor name. This handle is important because we need it to unregister scripts after the merge process is complete.

2.) Lack of flexibility. If there is addition or subtraction of a javascript file, we have to re-combine that file manually.

3.) It cannot be guaranteed that the combined pieces of code will not conflict. This has to do with the sequence of function calls and javascript variable scopes.

How to Combine Javascript Files in WordPress into One File - Automatically

To automatically merge javascript files in WordPresss, you first need to collect the paths to the javascript files along with the names of their handles (similar to manual method, only automatically).

We can find all the information about javascript files uploaded to WordPress page in the WP_Scripts object.

This object is stored in the $wp_scripts variable and is called in template sections such as wp_head, wp_print_scripts (wp_enqueue_scripts), wp_footer, init. Here are a couple of the most common cases.

Once. In the head (tag) we can define this using the wp_head hook.

Two. In the footer (before the tag) we can define this using the wp_footer hook.

Open the functions.php file for editing, located in the theme folder that is used, and add the code there:

Code: add_action("wp_head", "show_head_scripts", 9999);
add_action("wp_footer", "show_footer_scripts", 9999);

// Appear at the top, before opening body
function show_head_scripts())(
global $wp_scripts;
echo ""; print_r($wp_scripts->done); echo "";
}
// Appear below, after the basement
function show_footer_scripts())(
global $wp_scripts;
echo ""; print_r($wp_scripts->done); echo "";
}

Now we open the page, look at its source and see there lists of paths to JS files (at the top and bottom of the page).

Combining javascript files into one file in WordPress

To merge, you need to collect paths to files that can be detected automatically before the content is displayed. The wp_enqueue_scripts hook is suitable for this. There are some disadvantages to this (described below), but this is the only trick we can use automatically.

How this is done (description of code logic):

1.) The javascript file handle is copied according to its dependency so that after merging it can run without errors. We can do this by calling the all_deps method on the WP_Scripts object($wp_scripts->all_deps($wp_scripts->queue));

2.) Retrieving code in javascript files (using file_get_contents) and combining with others. Including the localize script wp_localize_script (if available). This script can be found in $ wp_scripts-> registered ["handle"] -> extra ["data"]

3.) Write the combined code to a file (using file_put_contents) and load it using the wp_enqueue_scripts function.

4.) Unregister all scripts/handles that have been merged, this is done after completing the process described in the previous paragraph (if we unregister a script, then its dependent script will also be unregistered).

To make the engine do all these tasks, paste the following code into the functions.php file:

Code: add_action("wp_enqueue_scripts", "merge_all_scripts", 9999);
function merge_all_scripts()
{
global $wp_scripts;

/*
#1. Reorder the handles based on its dependency,
The result will be saved in the to_do property ($wp_scripts->to_do)
*/
$wp_scripts->all_deps($wp_scripts->queue);

// New file location: E:xampp\htdocs\wordpresswp-content\theme\wdc\merged-script.js
$merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . "merged-script.js";

$merged_script = "";

// Loop javascript files and save to $merged_script variable
foreach($wp_scripts->to_do as $handle)
{
/*
Clean up url, for example wp-content/themes/wdc/main.js?v=1.2.4
become wp-content/themes/wdc/main.js
*/
$src = strtok($wp_scripts->registered[$handle]->src, "?");

/**
#2. Combine javascript file.
*/
// If src is url http / https
if (strpos($src, "http") !== false)
{
// Get our site url, for example: http://webdevzoom.com/wordpress
$site_url = site_url();

/*
If we are on local server, then change url to relative path,
e.g. http://webdevzoom.com/wordpress/wp-content/plugins/wpnewsman/css/menuicon.css
become: /wp-content/plugins/wpnewsman/css/menuicon.css,
this is for reduse the HTTP Request

If not, e.g. https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css,
then leave as is (we"ll skip it)
*/
if (strpos($src, $site_url) !== false)
$js_file_path = str_replace($site_url, "", $src);
else
$js_file_path = $src;

/*
To be able to use file_get_contents function we need to remove slash,
e.g. /wp-content/plugins/wpnewsman/css/menuicon.css
become wp-content/plugins/wpnewsman/css/menuicon.css
*/
$js_file_path = ltrim($js_file_path, "/");
}
else
{
$js_file_path = ltrim($src, "/");
}

// Check wether file exists then merge
if (file_exists($js_file_path))
{
// #3. Check for wp_localize_script
$localize = "";
if (@key_exists("data", $wp_scripts->registered[$handle]->extra)) (
$localize = $obj->extra["data"] . ";";
}
$merged_script .= $localize . file_get_contents($js_file_path) . ";";
}
}

// write the merged script into current theme directory
file_put_contents($merged_file_location, $merged_script);

// #4. Load the URL of merged file
wp_enqueue_script("merged-script", get_stylesheet_directory_uri() . "/merged-script.js");

// 5. Deregister handles
foreach($wp_scripts->to_do as $handle)
{
wp_deregister_script($handle);
}
}

Checking that the merger was successful

Go to the blog page, open the source and look for the connected merged-script.js file in it

Then make sure there are no errors in the combined script by opening your browser's "developer tools" (press F12 in Google Chrome) and select the Console tab.

The console displays the text of the error and references the location where it occurred. If there are no curse words on the merged-script.js file, then everything is ok.

Check the functionality of other scripts that did not participate in the merger.

Original article in english you cat read there.

Reading time: 2 minutes. Published 04/20/2017

Hello! We continue to analyze the most interesting and most useful plugins for the WordPress site! Today you will learn how to combine CSS and JS files to optimize your website. By default, all CSS and JS files are displayed separately, creating a load on the site. You can combine these files into one file to make the site load faster. Very simple and useful plugin!

You can install the plugin directly from the WordPress admin panel. Go to page: Plugins – Add new, enter the name of the plugin in the search form, press Enter, install and activate the plugin.


– Use Compass, check the box here to enable the plugin.

– Compass compiler’s path, the path of the file compiler is indicated here.

– Sass compiler’s path (required only for .sass format – not .scss), path (address) for CSS files.

– CoffeeScript compiler’s path, the path for scripts.

– Compress styles, optimize styles.

– Compress scripts, optimize scripts.

– Async attribute on footer’s script tag, load scripts asynchronously.

– Resources to exclude, here you can exclude certain scripts or styles.

– Activate Log, enable log file logging.

– Development Mode, if you enable this parameter, the cache will be deleted every time the page is reloaded.

– Save, save the changes.

– Empty AssetsMinify’s Cache, click on this tab to manually delete the cache.


All is ready! After saving the settings, all scripts and styles on your site will be combined into one file. This refers to scripts and styles that are displayed in source code your site. This way your site will load faster!

77

I'm trying to optimize site performance by consolidating and compressing CSS and JS files. My question is more related to the (specific) steps on how to achieve this, given the actual situation I encountered (although this should be common for other developers as well).

For a product release, I would like to combine 3 CSS files into one and compress it using, for example, YUI Compressor. But then I'll need to update all the pages that need those 3 files to link to the newly changed CSS. This seems error prone (e.g. you are deleting and adding some lines to many files). Any other less risky approach? Same problem for JS files.

  • 13 answers
  • Sorting:

    Activity

12

You can run it in an ant task and hence include it in your messages/pre commit hooks if you are using svn/git.

UPDATE: I'm currently using grunt with CONCAT, downplay & disfigure contributions. You can use it with an observer to have it create new minifiles in background every time the source changes. uglify contrib not only splits console logs, but also removes unused functions and properties.

19

I will need to update all pages that need these 3 files to link to the newly rooted CSS.

First, I would say that you should have a general title. So there is no need to change all the headers when necessary. A good practice is to have one heading or 2-3. Since your page is needed, you can change your title. So when you want to expand your web application, it will be less risky and tedious.

You didn't mention your development environment. You can see that there are many compressing tools listed for different environments. And you use good tool i.e.YUI Compressor.

6

I don't see you mention a content management system (Wordpress, Joomla, Drupal, etc.) but if you are using any popular CMS, they have all the plugins/modules available (free options) that will minimize and cache your css and js.

Using a plugin gives you the ability to keep uncompressed versions available for editing, and then when you make changes, the plugin automatically incorporates your changes and recompresses the file. Just make sure you choose a plugin that allows you to exclude files (eg. user file js) if it breaks anything.

I've tried in the past to keep these files manually and it always turns into a maintenance nightmare. Good luck, hope this helped.

3

If you're doing pre-processing of the files you're serving, you'll probably want to set up a proper build system (such as a Makefile). This way you have the original files without duplication, and whenever you make changes, you run "make" and update all the automatically generated files. If you already have a build system installed, learn how it works and uses it. If not, you need to add it.

So first figure out how to merge and minify your files from command line(see YUICompressor documentation). Designate a directory for automatically generated materials, separate from the material you are working on but accessible to the web server, and output there, for example gen/scripts/combination.js. Place the commands you used in the Makefile and repeat "make" every time you made a change and want it to take effect. Then update the headers in the other files to point to the combined and minifiles.

5

For people who want something a little more lightweight and flexible, I created js.sh today to solve this problem. It is a simple command line tool that targets JS files, which can be easily modified to take care of CSS files. Advantages:

  • Easily customizable for use by multiple developers on a project
  • Combines JS files in the order specified in script_order.txt
  • compress them with Google's Closure Compiler
  • Separates JS into< 25kb куски где возможно, так как iPhone не будет кэшировать что-либо большее, чем 25kb.
  • Creates a small PHP file with tags you can include where appropriate
  • Usage: js.sh -u yourname

It could use some improvements, but it's better for my use case than all the other solutions I've seen so far.

4

The first optimization step is to minimize files. (I highly recommend GULP for minification and optimization. Its a simple solution for hours, installation and all files are compressed at once. Supports all CSS, JS, less, sass, etc.)

OR Old school solution:

1) In general, as an optimization process, optimizing site performance, try merging all the CSS into one file and compress the file using Compass. This way your multiple requests for static CSS will be replaced with one.

2) The multiple JS problem, which you can resolve by using a CDN (or Google hosted Libraries) so requests go to a different server than yours. This way, the server does not wait for the previous request to complete before sending the next one.

3) If you have your own locally stored JavaScript, hide each file using the Brackets "Compress JavaScript" plugin. It's basically one click to compress JavsScript. Brackets - free editor for CSS and JS, but can be used for PHP and other languages. There are many plugins to choose from for both front-end and third-party developers. In general, “one click” to execute all these (still multiple) commands. Btw, brackets replaced my very expensive Dreamweaver ;)

3) Try using tools like Sass, Compass, less to minimize CSS.

Note: Even without using blending or variables, your CSS will be compressed (simple use pure CSS and the Compass "look" command compresses it for you).

Hope this helps!

1

In my symphony project I do something like this

(#layout.html.twig #) (% block styles %) (% if app.environment == "prod" %) (% else %) (% endif %) (% endblock %) (# some-view.html .twig #) (% extends "AppMainBundle::layout.html.twig" %) (% block styles %) (( parent() )) (% if app.environment != "prod" %) (% else %) (%endblock%)

When the DEV version is ready for production I use

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax Object.assign(target , ... sources) Parameters target The target object - what to apply the sources’ properties to, which is returned after it is modified. sources The source object(s) - objects containing the properties you want to apply. Return value

The target object.

Description

Properties in the target object are overwritten by properties in the sources if they have the same key . Later sources" properties overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [] on the source and [] on the target, so it will invoke getters and setters . Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.

Examples Cloning an object const obj = ( a: 1 ); const copy = Object.assign((), obj); console.log(copy); // ( a: 1 ) Warning for Deep Clone

For deep cloning, we need to use alternatives, because Object.assign() copies property values.

If the source value is a reference to an object, it only copies the reference value.

Function test() ("use strict"; let obj1 = ( a: 0 , b: ( c: 0)); let obj2 = Object.assign((), obj1); console.log(JSON.stringify(obj2) ); // ( "a": 0, "b": ( "c": 0)) obj1.a = 1; console.log(JSON.stringify(obj1)); // ( "a": 1, "b": ( "c": 0)) console.log(JSON.stringify(obj2)); // ( "a": 0, "b": ( "c": 0)) obj2.a = 2 ; console.log(JSON.stringify(obj1)); // ( "a": 1, "b": ( "c": 0)) console.log(JSON.stringify(obj2)); // ( " a": 2, "b": ( "c": 0)) obj2.b.c = 3; console.log(JSON.stringify(obj1)); // ( "a": 1, "b": ( " c": 3)) console.log(JSON.stringify(obj2)); // ( "a": 2, "b": ( "c": 3)) // Deep Clone obj1 = ( a: 0 , b: ( c: 0)); let obj3 = JSON.parse(JSON.stringify(obj1)); obj1.a = 4; obj1.b.c = 4; console.log(JSON.stringify(obj3)); // ( "a": 0, "b": ( "c": 0)) ) test();

Merging objects const o1 = ( a: 1 ); const o2 = ( b: 2 ); const o3 = ( c: 3 ); const obj = Object.assign(o1, o2, o3); console.log(obj); // ( a: 1, b: 2, c: 3 ) console.log(o1); // ( a: 1, b: 2, c: 3 ), target object itself is changed. Merging objects with same properties const o1 = ( a: 1, b: 1, c: 1 ); const o2 = ( b: 2, c: 2 ); const o3 = ( c: 3 ); const obj = Object.assign((), o1, o2, o3); console.log(obj); // ( a: 1, b: 2, c: 3 )

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties const o1 = ( a: 1 ); const o2 = ( : 2 ); const obj = Object.assign((), o1, o2); console.log(obj); // ( a: 1, : 2 ) (cf. bug 1207182 on Firefox) Object.getOwnPropertySymbols(obj); // Properties on the prototype chain and non-enumerable properties cannot be copied const obj = Object.create(( foo: 1 ), ( // foo is on obj"s prototype chain. bar: ( value: 2 // bar is a non-enumerable property. ), baz: ( value: 3, enumerable: true // baz is an own enumerable property. ) )); const copy = Object.assign((), obj); console.log(copy) ; // ( baz: 3 ) Primitives will be wrapped to objects const v1 = "abc"; const v2 = true; const v3 = 10; const v4 = Symbol("foo"); const obj = Object.assign(() , v1, null, v2, undefined, v3, v4); // Primitives will be wrapped, null and undefined will be ignored. // Note, only string wrappers can have own enumerable properties. console.log(obj); // ( "0": "a", "1": "b", "2": "c" ) Exceptions will interrupt the ongoing copying task const target = Object.defineProperty((), "foo", ( value: 1 , writable: false )); // target.foo is a read-only property Object.assign(target, ( bar: 2), ( foo2: 3, foo: 3, foo3: 3), ( baz: 4 )) ; // TypeError: "foo" is read-only // The Exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1, exception is thrown here. console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied. console.log(target.baz); // undefined, the third source will not be copied either. Copying accessors const obj = ( foo: 1, get bar() ( return 2; ) ); let copy = Object.assign((), obj); console.log(copy); // ( foo: 1, bar: 2 ) // The value of copy.bar is obj.bar"s getter"s return value. // This is an assign function that copies full descriptors function completeAssign(target, ...sources) ( sources.forEach(source => ( let descriptors = Object.keys(source).reduce((descriptors, key) => ( descriptors = Object.getOwnPropertyDescriptor(source, key); return descriptors; ), ()); // By default, Object.assign copies enumerable Symbols, too Object.getOwnPropertySymbols(source).forEach(sym => ( let descriptor = Object .getOwnPropertyDescriptor(source, sym); if (descriptor.enumerable) ( descriptors = descriptor; ) ); Object.defineProperties(target, descriptors); )); return target; ) copy = completeAssign((), obj); console.log(copy); // ( foo:1, get bar() ( return 2 ) ) Polyfill

This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway:

If (typeof Object.assign !== "function") ( // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", ( value: function assign(target, varArgs) ( // .length of function is 2 "use strict"; if (target === null || target === undefined) ( throw new TypeError("Cannot convert undefined or null to object"); ) var to = Object( target); for (var index = 1; index< arguments.length; index++) { var nextSource = arguments; if (nextSource !== null && nextSource !== undefined) { for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to = nextSource; } } } } return to; }, writable: true, configurable: true }); }

Specifications Specification
ECMAScript Latest Draft (ECMA-262)
The definition of "Object.assign" in that specification.
Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsassign
Chrome Full support 45Edge Full support 12Firefox Full support 34IE No support NoOpera Full support 32Safari Full support 9WebView Android Full support 45Chrome Android Full support 45Firefox Android Full support 34Opera Android Full support 32Safari iOS Full support 9Samsung Internet Android Full support 5.0nodejs Full support 4.0.0
Legend Full support Full support No support No support