You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Current »

A common approach load remote JS code is to use <script src="..."></script>, but sometimes you will be required to load the remote JavaScript code dynamically. Then you can simple do it by creating script element by document.createElement('script')

Below is an example to load JavaScript code in the header

function load_javascript_header(url) {
	const script = document.createElement("script");
	script.type="text/javascript";
	script.src = url;
	script.async = true;
	script.crossorigin = "anonymous";
	document.head.appendChild(script);
	eval(script);
}


Below is an example to load JavaScript code in the body:

function load_javascript_body(url) {
	const script = document.createElement("script");
	script.type="text/javascript";
	script.src = url;
	script.async = true;
	script.crossorigin = "anonymous";
	document.body.appendChild(script);
	eval(script);
}
  • No labels