I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.
For example, I would like to include my js files like,
<script src="single.js?files=first.js,second.js,third.js..."></script>
How can I do that in an efficient manner?
To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
i hope its use full
You can use the jQuery.getScript()
function... I think it will be much easier to you with this to include a JavaScript .js
file.
Here is the reference.
there are many different ways, but the way Google loads additional scripts is like this:
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
This is taken directly from Google maps loader.
Writing a script tag directly to the document is the simplest and most efficient way.
Following the advice of Salaman A's comments, I found how Google does it now with Analytics: https://developers.google.com/analytics/devguides/collection/gajs/asyncTracking
And here is a more generic version of the same code:
(function() {
var s = document.createElement('script'); // Create a script element
s.type = "text/javascript"; // optional in html5
s.async = true; // asynchronous? true/false
s.src = "//example.com/your_script.js";
var fs = document.getElementsByTagName('script')[0]; // Get the first script
fs.parentNode.insertBefore(s, fs);
})();
To add a new javascript file dynamically:
function includeJS(jsFile) {
$('head').append($('<script>').attr('type', 'text/javascript').attr('src', jsFile));
}
// Pick a JS to load
if ($.browser.msie) {
includeJS('first.js');
} else {
includeJS('second.js');
}
includeJS('third.js');
I've seen what the scriptaculous loader does. What it does is that it goes through all script tags in the document to find the one that loaded itself, e.g:
<script src="/path/to/single.js?files=first.js,second.js,third.js"></script>
Then it parses the querystring used inside the src attribute and dynamically create additional script tags for each script file. At the same time it also parses the path of the base script (/path/to/single.js
) and uses the same path to load dependency files (e.g. /path/to/first.js
).
You can create your own script loader like this. In vanilla javascript, you can use the following functions:
getElementsByTagName
-- find all scriptsgetAttribute
-- find src/href/type attributecreateElement
-- create a script elementappendChild
-- append to head/body
Anand Thangappan has posted a solution that uses these functions. If you're using a framework such as jQuery or MooTools then both provide their own implementations of dynamically loading JsvaScript.
Finally, there is a server side solution for your problem. Look at minify -- Combines and minifies multiple CSS or JavaScript files into a single download.
We can quickly extend this so that a callback can be performed once the script is added.
function loadjscssfile(filename, filetype, callback){
if (typeof fileref!="undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
callback();
}
}
document.getElementsByTagName("head")[0].appendChild(fileref)
is not working if you have some document.ready() works inline. $("head").append(fileref);
works great for me, although it needs jquery.min.js
inline reference.
<head>
<!-- Meta, title, CSS, favicons, etc. -->
<script src="script/jquery.min.js"></script>
<script src="script/master_load.js"></script>
<script>
load_master_css();
load_master_js();
</script>
</head>
and master_load.js
:
function loadjscssfile(filename) {
if (filename.substr(filename.length - 4) == ".css") { // 'endsWith' is not IE supported.
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("href", filename)
//fileref.setAttribute("type", "text/css")
}
else if (filename.substr(filename.length - 3) == ".js") {
var fileref = document.createElement('script')
fileref.setAttribute("src", filename)
//fileref.setAttribute("type", "text/javascript")
}
$("head").append(fileref);
}
function load_master_css() {
loadjscssfile("css/bootstrap.min.css");
// bunch of css files
}
function load_master_js() {
loadjscssfile("script/bootstrap.min.js");
// bunch of js files
}
来源:https://stackoverflow.com/questions/5751620/ways-to-add-javascript-files-dynamically-in-a-page