Skip to main content

How To Easily Preload Images / CSS / JS With Javascript

By September 1, 2017Blog, Javascript
Allure Web Solutions Code Snippet

With this snippet you can easily preload your images, css, js. The script initiates after the page loaded so it doesn’t affect loading time.

window.onload = function() {

	setTimeout(function() {

		// reference to <head>
		var head = document.getElementsByTagName('head')[0];

		// a new CSS
		var css = document.createElement('link');
		css.type = "text/css";
		css.rel  = "stylesheet";
		css.href = "http://domain.tld/preload.css";

		// a new JS
		var js  = document.createElement("script");
		js.type = "text/javascript";
		js.src  = "http://domain.tld/preload.js";

		// preload JS and CSS
		head.appendChild(css);
		head.appendChild(js);

		// preload image
		new Image().src = "http://domain.tld/preload.png";

	}, 1000);

};

// Credits: https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

 

allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017