Using Javascript to load other external Javascripts - javascript

I have a library of JS code to load from a folder.
Instead of typing the <script src='...'></script> lines one by one in the tag of the HTML document, is there a way of just link one Javascript file which organizes and automatically load other javascript files.
I know the Dojotoolkit is using this technique where only one JS file is loaded onto the client's computer, and once the code has been requested in the browser, 20 other JS code each with <script> tag are generated.

This is the code you need:
// Create
var bodyEl = document.body;
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = url;
bodyEl.appendChild(scriptEl);
Put that into a function, have an array of all the javascript files, and call that function for each file.
Benefits of using the DOM is that document.write doesn't work in some funny instances. More about this here:
document.write() vs inserting DOM nodes: preserve form information?
Code taken from the open source project jQuery Sparkle:
http://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.appendscriptstyle.js#L103

A simple way to do that:
document.write("<script type='text/javascript' src='b.js'></script>");

Try use requireJs, he have very userful functions
Official website

Related

Load JavaScript file source code as plain text and access its content using JavaScript

Is it possible to download a script file using the script tag like this
<script src="http://webserver.com/script.js"></script>
and then be able to read the loaded file content with JavaScript, like this for example:
var scriptContent = window.scripts[0].content;
What i came to notice is that the loaded JavaScript file contents is not accessible by other JavaScript files or am i wrong ?
No, it is not possible to do that.
The source code of a script loaded via src is not exposed via any API made available to JavaScript running in the page.
You could read the value of src and then fetch it using XMLHttpRequest.
The source code of specific functions may be available by calling toString() on them.

Is it possible to locally replace a website's Javascript when the page loads?

I am not talking about using an add-on such as greasemonkey to inject new javascript. I'm talking about providing (possibly a browser extension of some sort) a custom js script to be loaded instead of the one that the page provides.
Example:
Page has <script src="script.js"></script>
I would like to tell my browser to run X code instead of what was in script.js
Thank you. Sorry if the question is not very clear.
There are a few ways to programmatically execute Javascript on a web page.
Add Another Script Tag
If you can save your script on the web somewhere, then you can just insert a new script tag referencing it.
var script = document.createElement('script');
script.setAttribute('src', 'http://yourscript.com/script.js');
document.body.appendChild(script);
Alternatively, if you can find the existing script tag, you can just change the source.
var script = document.getElementById('my-script');
script.setAttribute('src', 'http://yourscript.com/script.js');
Eval the Code
If you already have the code you want to execute, then you can write a script that uses Javascript's eval function to run it.
var code = '...';
eval(code);
Warning! Unless you absolutely trust the source of the code, then using eval can be dangerous.
Try this, this will inject a script element into the page. I am finding the way to remove the existing element.
<script type="text/javascript">
document.write("<script src='codex.js'></script>");
</script>
Open the developer tools in chrome (F12 on windows), navigate to your .js source file, then proceed to promptly modify what you see in the editor that is presented. Chrome only persists these changes as long as the page doesnt get refreshed. Once the page is refreshed it drags files from the server again and your local changes will be lost.
You can do a replace of the code in that file.
Hope this was what you were looking for!

including external javascript file

I am trying to include external javascript to a document. Let's say that external js has the following code.
function myFunction() {
console.log("hello");
}
and I include it from console by
var script = document.createElement('script');
script.src = "http://myjs";
document.getElementsByTagName('head')[0].appendChild(script);
but then I still get myFunction() is undefined error. The function is being called from php file included on the page somehow. Interestingly, appending my external javascript right after the head tag in the document was not enough for it to precede the function call from the loaded php file.
Q: how do I ensure that I include my javascript BEFORE the php file given my situation?
EDIT: this is the hierarchy of all the sources
mysubsite.com
myfolder
mypage.html
mysite.com
myfolder
main.php
problem.php
problem.php is calling function myFunction() but it's not included anywhere yet. So I try to define the function in an outside js file and include it in mypage.html, but problem.php still comes before the included javascript in mypage.html
EDIT:
I think the real problem is that I am dealing with an iframe that's included inside a main document. In this case, is there a way to include my external javascript file inside the main document from console? Including scripts from console only affects the iframe instead of the main document.
What you're doing is fine, but then you have to wait for the file to load. Most browsers will raise the load event on the script element although some older versions of IE use onreadystatechanged instead. But since you're using jQuery (from the tags on the question), you don't have to worry about that, you can just use $.getScript:
$.getScript("http://myjs", function() {
// The script has been loaded, you can call myFunction now
});
PHP is always included before JavaScript. PHP is executed by the server before it's sent to the client, and JavaScript is executed by the client.
Why can't you just put a regular <script type="text/javascript" src="http:/myjs"></script> in your head?

How to dynamically load a file on a specific line in JavaScript?

I created this script for a core.js file for my client's website and I want to dynamically load a few javascript libraries from that core.js file. However, javascript libraries require that you load that library first, then use the rest of your script, because you have to define your libraries object before calling it, doh. So I have this very simple script to dynamically load a file, but I want to know if there's a method to make sure that it loads it in priority ahead of the core.js file. Here's the current script:
(function() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://modernizr.com/downloads/modernizr-latest.js");
if(typeof script != "undefined") {
document.getElementsByTagName("head")[0].appendChild( script );
}
})();
And in the debugger, you see:
Of course, it's going to load the dynamic file ahead of the core file, but I was wondering if there was a way to specify the line on the document for which to load the modernizr file? Otherwise, I can't use Modernizr, even though I have loaded it.
Obviously, I can't use jQuery, because I want to load that, too.
You can respond to the loading of a dynamically-loaded JavaScript resource (or any resource, for that matter -- image, iframe, video, etc.) with a load event listener. The easiest way to do it here would be:
(function() {
var script = document.createElement("script");
...
script.onload = function() {
// this will run later, when the script loads
// in this function you can safely use Modernizr
}
})();

Conditional "Get Script File" in Javascript without using a library function

I work at a company that has many clients that have their own website that "plugs in" to our system. In other words they have their own website and they have a link that, when the user clicks it, transitions them over to our site.
There is a feature that I want to track by giving the client a small block of code to put on their homepage. Whenever the homepage is loaded with a certain query string variable I want the block of code to request a file on my server. Then on the server I'll record the tracking info based on the query string.
All this would be really easy if I can guarantee that the client would be using jQuery or some similar library, but there are a lot of clients and I can't really rely on them all using jQuery. At the same time I'd like to limit the size of the block of javascript code that they paste in.
I think the best solution would be to have something like:
if(querystring.substring("Tracking=") > 0)
{
include("blah.aspx?TrackingQS=" + querystring);
}
but I can't find a include function in built-in javascript without calling some library like jQuery.
Any thoughts?? I could do straight up AJAX but I want to limit the number of lines of code for several reasons that I won't bore you with here.
Add a script block programmatically
function include(path) {
var s = document.createElement('script');
s.type = 'text/javascript'
s.src = path;
document.getElementsByTagName('head')[0].appendChild(s);
}
As an enhancement, you can keep track of all the paths that have been added so that you dont accidentally load the same script twice.
Typically one does this by inserting a 1x1 img tag whose src is your blah.aspx.
Write a script that would use the built-in Ajax methods and give your clients this:
<script type="text/javascript" src="yourScript.js"></script>
You could give them something like this:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.1");
ourJQ = jQuery.noconflict();
//jQuery code
</script>
That will load jQuery from Google which will save them bandwidth and let you use jQuery.

Categories

Resources