I am using following code inside my HTML to load a JS file after page load.(DOMContentLoaded)
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
});
</script>
But I got several scripts to load and I have no idea how to implement this for multiple scripts.
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.0.0/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
Your help with this would be greatly appreciated. Thanks.
As mentioned in the comments, you could look at using a module loader.
If you want to do it without a module loader, then you have the right idea. To keep the code easier to read/shorter, you could create an array of urls and iterate through them and appending a new script element for each.
const jsFiles = [
'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js',
'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js',
'https://ajax.aspnetcdn.com/ajax/bootstrap/4.0.0/bootstrap.min.js',
'https://cdn.jsdelivr.net/npm/sweetalert2#8'
]
jsFiles.forEach((item) => {
const scriptEle = document.createElement('script');
scriptEle.src = item;
document.head.appendChild(scriptEle);
})
Related
I am using following code inside my HTML to load a JS file after page load.(DOMContentLoaded)
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
});
</script>
But I have several scripts to load and I have no idea how to do this in the best possible way. For example, I have following files to link.
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.0.0/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
Any help would be greatly appreciated.
If you know upfront the script names you can define an array like:
var scripts = ["script1.js", "anotherscript.js", "whatever.js"];
And then loop through it, and for each script you can append it as you did before
var scriptName;
for (scriptName in scripts) {
// create the script and set the src = scriptName as before
}
Can we realize dynamically loading, of js, css and other files, process?
By getting all needed info (what we must to load) from html tags data attributes?
For example:
<html>
<head>
<title>Our app</title>
</head>
<body data-load-css="style">
<div class="all" data-load-js="jquery|jqueryui" data-load-js-type="async">
<div class="header" data-load-js="main">
Header
</div>
<div class="body" data-load-js="body">
Body
<div class="some-tipsy" data-load-css="tipsy"></div>
</div>
<div class="footer" data-load-js="other">
Footer
<div class="some-other" data-load-css="other"></div>
</div>
</div>
<script>
// our js app to load dynamically js, css
</script>
</body>
</html>
So, maybe you have some ideas how do it in best way? With the best performance and flexibility.
Or I just need to use require js, and don't worry about some "new things"?
If just require js, then how do it best with this js plugin? To load all stuff most dynamically?
And how solve problem with js async, defer loding? Where some scripts must be loaded in specific order.
Here is my continued version 2 of current question: https://stackoverflow.com/questions/34413940/dynamically-load-js-files-by-html-data-attr-dependencies
Following are few ways to load scripts dynamically:
Javascript: Write a custom load function.
jQuery: $.getScript(). For css refer SO-Post.
require.js: require(moduleName)
ECMA 6: import
Following is a pure javascript function to load scripts dynamically:
function(url, callback) {
var scripts = utils.getLoadedScripts(); // Read all scripts and push names in array.
var lastIndex = url.lastIndexOf("/");
var isLoaded = false;
scripts.forEach(function(row, index) {
if (row == url.substring(lastIndex + 1)) {
isLoaded = true;
return;
}
});
if (!isLoaded) {
//$(".reveal").addClass("loading");
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.name = "url";
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
};
You could make use of web workers in your case. You can process the code asynchronously to do the task asynchronously.
Main script:
var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage(); // Starts the worker to work;
doWork.js (the worker):
self.addEventListener('message', function(e) {
self.postMessage("Hi, loaded async."); // send the data via postMessage to main script.
}, false);
So, what it means you can put your logic inside doWork.js and put the scripts asynchronously to the user's screen.
I have a script (Google Maps, to be exact) that is loading dynamically, and for a couple of reasons, I cannot alter how this initially loads by default.
Through JavaScript, I would like to find the string libraries=places and change it to libraries=places,visualization after the fact
So, the originally output:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places">
</script>
Would be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=places,visualization">
</script>
Is this even possible?
Thanks In Advance
this solution should apply to yours as well:
How do I include a JavaScript file in another JavaScript file?
script.src = url; will be the line where you add the src url however you like
First of all Give the google map script tag an ID:
<script id="google_map_script" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Then do:
var google_map_script = document.getElementById("google_map_script")
google_map_script.setAttribute("src", "https://maps.googleapis.com/maps/api/js?libraries=places,visualization")
Edit: since apparently this isn't what is needed then what about this:
var script = document.createElement('script');
my_awesome_script.setAttribute('src','https://maps.googleapis.com/maps/api/js?libraries=places,visualization');
document.head.appendChild(script);
Also have a look into using postscribe.
In my project requirement I need to add java script dynamically
I have a js file global.js which contains all global variable that I want to add dynamically.
I also want to add global.js before util.js( which uses variable defined in global.js) which is not happening
If I open page source I can't see the global.js added there
I also want this to be work in all browser mainly in ie6 and ie8
my code Index.html
<script src="../fw.ui.lib/resources/sap-ui-core.js" id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons, sap.ui.table, sap.ui.ux3"
data-sap-ui-theme="sap_goldreflection">
</script>
<script src="../fw.ui/js/application_properties.js" type="text/javascript"></script>
<script src="../fw.ui/js/header.js" type="text/javascript"></script>
<script src="../fw.ui/js/dao/userDAO.js" type="text/javascript"></script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script src="js/controls/DynamicJsLoad.js" type="text/javascript"></script>
<script></script>
<script>addScriptDynamically()</script>
<script src="js/controls/util.js" type="text/javascript"></script>
DynamicJsLoad.js
function loadScript(url){
var e = document.getElementsByTagName("script")[5];
var d = document.createElement('script');
d.src = url;
d.type = 'text/javascript';
d.async = false;
d.defer = true;
e.parentNode.insertBefore(d,e);
}
function addScriptDynamically(){
var scheme = getCacheBurstScheme();
if( scheme == 'dev'){
scheme = new Date();
}
loadScript('js/global.js'+'?scheme='+scheme);
}
If you are using jQuery anyway, you could leverage their loadScript() function. An example from their website:
$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
// [...]
});
Regarding your current solution, here are a couple of hints:
You set defer = true, which will defer loading (and executing) of your dynamically loaded script to the end. Thus after util.js. I don't think you want that
Dynamically loaded js sources do not appear in your page's source code. You might need to use a tool like Firebug to validate if things have loaded.
I used Jquery to insert a variable to div. Please check my code.
var msg = '<script src="https://gist.github.com/3010234.js?file=new.html.erb"></script>'
$('.result').html(msg);
msg variable contains a script that render a code snippet. msg is dynamic variable.
The above code is not working to insert code snippet to div.
Any Idea?
This script generate code snippet like this.
To add script, I would add it to head like this;
var s = document.createElement('script');
s.src = 'https://gist.github.com/3010234.js?file=new.html.erb';
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
You cannot load a github gist into a page dynamically using that embed code. The embed code is fine if you can add the script tag to the HTML, but to do it dynamically via JavaScript as you are trying to do, it won't work because it relies on document.write().
Instead, use the github gists api:
$.get("https://api.github.com/gists/3010234", function(response) {
$(".result").text(response.data.files["new.html.erb"].content);
}, "jsonp");
Working demo: http://jsfiddle.net/naTqe/
function loadScript() {
var script = document.createElement("script");
script.src = "https://gist.github.com/3010234.js?file=new.html.erb";
script.type = "text/javascript";
document.getElementById("result").appendChild(script);
}
It looks like your remote JS is buggy. I ran it through JS Lint and came up with several errors.
Anyway, here is my working example. Keep a javascript console open and you'll see the error when it tries to parse the remote JS.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Jquery test</title>
</head>
<body>
<h1>jQuery</h1>
<p class="result">Some result</p>
<script>
/*<![CDATA[*/
$(document).ready(function(){
var msg = '<script type="text/javascript" src="http://gist.github.com/3010234.js?file=new.html.erb"><\/script>";
$('.result').html(msg);
});
/*]]>*/
</script>
</body>
</html>