The Most Secure Cross Browser Testing Platform since 2012

6 JavaScript Features Available Cross Browser Today

BLOG / BrowseEmAll / Browsers / Cross Browser Testing / Multibrowser / Web Development

6 JavaScript Features Available Cross Browser Today

JavaScript is one of the most widely used languages in web development, but it can take time for new features to be supported across all browsers. Fortunately, modern browsers are rapidly evolving, allowing us to use many powerful JavaScript features seamlessly. Asynchronous scripts that improve page load times, IndexedDB for handling large datasets, full-screen mode for enhanced user experience, and Web Workers for running tasks in the background are now supported in all major browsers. In this article, we’ll explore six JavaScript features you can use today without worrying about browser compatibility.

Async Script Execution

In web pages, JavaScript files are executed sequentially by default, meaning that a script must be loaded and executed before the rest of the page can continue rendering. This can negatively impact page load times, especially for external scripts such as analytics tools or ads. With the Async Script Execution feature, a script can be loaded in parallel with the HTML and executed as soon as it is ready. To enable this, simply add the async attribute to the <script> tag. This allows the script to load alongside the page and execute once it’s fully loaded, improving overall performance.

<script src="script.js" async></script>

JSON Support

JSON (JavaScript Object Notation) is a lightweight and readable data format commonly used in web development. When exchanging data via APIs or storing and transmitting information, JSON provides great convenience with its simple and flexible structure. Since JSON support is built into JavaScript, converting objects to JSON format and turning JSON data back into objects is straightforward. The JSON.stringify() method converts an object into JSON format, while the JSON.parse() method converts JSON data back into a JavaScript object, making it usable. This enables seamless data sharing across browsers, storage, and API integration.

// Convert an object to JSON format
const person = { name: "John", age: 30 };
const jsonString = JSON.stringify(person);
console.log(jsonString); // {"name":"John","age":30}

// Convert JSON data back to an object
const newPerson = JSON.parse(jsonString);
console.log(newPerson.name); // John

Data Storage with IndexedDB

IndexedDB is a database system used to store large amounts of structured data in web browsers. This feature is particularly useful when you need to store data locally in the user’s browser and avoid making a server request every time. IndexedDB stores data in key-value pairs and provides relational database features, enabling more complex data queries and operations. It is supported by all major browsers and allows applications to work independently from the server, improving performance.

// Open the IndexedDB database
let request = indexedDB.open("myDatabase", 1);

// Function that runs when the database is created or upgraded
request.onupgradeneeded = function(event) {
  let db = event.target.result;
  if (!db.objectStoreNames.contains("people")) {
    db.createObjectStore("people", { keyPath: "id" });
  }
};

// Function that runs when the database is successfully opened
request.onsuccess = function(event) {
  let db = event.target.result;
  let transaction = db.transaction("people", "readwrite");
  let store = transaction.objectStore("people");

  // Adding new data
  let person = { id: 1, name: "John", age: 30 };
  store.add(person);
};

// Function that runs in case of an error
request.onerror = function(event) {
  console.error("Database error: " + event.target.errorCode);
};

Full-Screen API

The Full-Screen API allows web pages to display their content in full-screen mode. It is particularly useful in interactive content like video players or games, enhancing the user experience. To enable full-screen mode, you may need to use appropriate vendor prefixes for different browsers. However, all major browsers support this API, with Microsoft Edge being the exception. The Full-Screen API allows content to occupy the entire screen, providing users with more screen real estate.

// Select the video element to go full-screen
var video = document.getElementById("videoTag");

// Use different browser prefixes to request full-screen mode
if (video.requestFullscreen) {
  video.requestFullscreen();
} else if (video.msRequestFullscreen) {
  video.msRequestFullscreen();
} else if (video.mozRequestFullScreen) {
  video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
  video.webkitRequestFullscreen();
}

Background Processes with Web Workers

Web Workers allow you to run JavaScript code in the background on a separate thread, without affecting the performance of the main UI thread. This is particularly useful for tasks that take a long time to process, such as data calculations, API calls, or large file processing. By offloading these tasks to Web Workers, the main thread remains free to handle user interactions, keeping the application responsive. Web Workers can communicate with the main thread using message passing, allowing you to update the UI with progress or results as needed.

// Create a new Worker
var worker = new Worker('worker.js');

// Send a message to the worker
worker.postMessage('Start processing');

// Listen for messages from the worker
worker.onmessage = function(event) {
  console.log('Received from worker: ' + event.data);
};

// worker.js
self.onmessage = function(event) {
  // Perform a long-running task (e.g., a calculation)
  let result = event.data + ' processed';
  // Send the result back to the main thread
  self.postMessage(result);
};

Geolocation API

The Geolocation API allows web applications to access the user’s geographical location, which can be used in various scenarios like providing location-based services, maps, or customized content. When using this API, the user must grant permission for the application to access their location data. It provides methods to get the current position, watch the position for changes, and handle errors if the location is unavailable. This API is widely supported across major browsers, making it a useful tool for location-based functionality.

// Request the geolocation of the user
navigator.geolocation.getCurrentPosition(function(position) {
  // Use the position object to get latitude and longitude
  console.log('Latitude: ' + position.coords.latitude);
  console.log('Longitude: ' + position.coords.longitude);
}, function(error) {
  // Handle the error case (e.g., user denied location access)
  console.error('Error occurred: ' + error.message);
});

In conclusion, the features discussed Async Script Execution, JSON support, IndexedDB, Full-Screen API, Web Workers, and Geolocation API are powerful tools that are now widely supported across major browsers. By utilizing these features, developers can enhance the performance, interactivity, and user experience of their web applications. With the continued advancement of browser technology, these capabilities will only become more essential in building efficient, responsive, and feature-rich websites. Whether you’re optimizing performance with asynchronous scripts, handling large datasets with IndexedDB, or providing personalized content with geolocation, these modern JavaScript features are key to creating seamless web experiences.