google.load custom js - javascript

I am using google ajax api
How can I load custom js which depends on libs loaded by ajaxapi?

You could define a function that inserts the script object into the DOM like
<script type="text/javascript">
function loadMyCustomJavaScript() {
var script = document.createElement("script");
script.src = "http://www.example.org/my.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
</script>
and either use it as google.setOnLoadCallback
<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
google.load("jquery", "1");
google.setOnLoadCallback(loadMyCustomJavaScript);
</script>
or, if you want to load it with a specific Google library that you load, as a callback for that method, ie.
<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
google.load("maps", "2");
google.load("search", "1", {"callback" : loadMyCustomJavaScript});
</script>
Update: Based on your comment, you could try to use jQuery.getScript which provides a callback function for the (externally) loaded JavaScript code. According to HubLog: Google, jQuery and plugin loading, you may have to use window.setTimeout to delay the execution of a function until the script(s) has/have eval'd.
Since jQuery and it's plugins are probably loaded asynchronously, you may need to use unobtrusive JavaScript instead of using jQuery/plugin functions in the HTML code directly.

Related

How do I link scripts externally and internally?

I have a website that I want to work online and offline. I want to decrease load time, so I minified the slow loading scripts. It didn't work enough. Locally, some of the scripts are taking 4-6 seconds to load.
I know that linking scripts externally speeds it up drastically. I have tried it and it works. But some of the users will not have internet access. Is there a way to link a group of scripts to an external site, and locally if they do not have internet access?
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="ui/jquery-ui.min.js" type="text/javascript"></script>
You can do something similar to this answer. Basically, the idea is that you attempt to load the Internet based script for jQuery. Afterward, you do a normal script where you check if jQuery === undefined. If it does, you want to load the local copy.
Basically, an example of what you want to do:
<script src="[jQueryURL]" type="text/javascript"></script>
<script src="[dataTablesURL]" type="text/javascript"></script>
<script src="[jQueryUIURL]" type="text/javascript"></script>
<script type="text/javascript">
if(jQuery === undefined) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/jquery-1.9.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
//repeat for other two scripts here
}
</script>
What will happen is that it will attempt to load the scripts in question, and afterward it will check if jQuery is defined. If it's not, that means the scripts didn't load, so you want to load the local versions and append them to your header.
Ensure that the script declares a global variable you can test for. Then generate a local script loading element if the external script fails to load (which you can determine by testing for that variable).
<script src="http://example.com/example.js"></script>
<script>
if !(window.Example) {
document.write('<script src="../scripts/example.js"><\/script>');
}
</script>
<script type="text/javascript">
if(navigator.onLine)
{
alert("Connected");
}
else
{
alert("Not Connected");
}
</script>
First Check if internet connection exist then load external file other wise load internal file

Can you automatically choose between two <script src=""> files?

So lets say you're implementing a website that uses jQuery HEAVILY. You could put some code like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and import it from some repository. If you're developing it without internet you could download the source and store it somewhere locally, then access it with some script like
<script src="js/jquery-1.10.2.min.js"></script>
But is there a simple way to have both? Such as if you can reach the repository use that, but if you can't use the local copy.
Check for a variable in the first script. If it is not found, use document.write to create the second script tag. Here is an example for jQuery I found here:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="js/jquery-1.7.1.min.js"><\/script>')</script>
The fail-safe way of referencing scripts on a CDN is to link to the local copy only if the CDN has failed for any reason.
The way to do this is simply to check if anything within the script has executed. For jQuery this is simply checking whether jQuery exists:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
if (!window.jQuery) document.write('<script type="text/javascript" src="/path/to/jquery-ver.sion.min.js"><\/script>');
</script>
Personally I have never had a script fail due to a CDN being offline, however I have had periods of internet outage. With scripts set up with a proper fallback, I've been able to continue local development as the pages still work without needing to connect to a CDN.
You can add resources dynamically if required one is not available. for eg:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
if( typeof $ != "function")
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'js/jquery-1.10.2.min.js';
head.appendChild(script);
}
</script>
</head>
<body>
</body>
</html>
Though JQuery hosted on Google CDN should be safe enough, the codes below can be used as a fallback with requireJS.
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
'//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
'js/jquery-ui.min.js'
]
}
});
require(['jquery'], function ($) {
});

Wait for jQuery to load

I'm trying to check if jQuery is loaded. If not, load it, then proceed to load external javascript files. The issue I'm having is one of the external files expects to have jQuery already loaded, so I get a 'jQuery not defined" error. Is there a way I can load jQuery using JavaScript, and as soon as it's done then continue?
if(!window.jQuery){
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
//load these scripts after jquery has been loaded
<script src="/some/other/js/file/that/requires/jquery"></script>
<script src="/some/other/js/file/that/requires/jquery"></script>
What I'd like to do is wait for this to completely load before continuing. I tried this but I got errors about exceeding call stack
Consider the technique tried and tested by HTML5Boilerplate instead:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
Note that <script src="//ajax.googleapis.com only works on an actual http: or https: server; if you're testing on a local filesystem, write <script src="http://ajax.googleapis.com instead.

Not defined function from $.getScript

This one must be very simple. An external javascript file contains:
function Hello() {
alert('Hello');
}
It is getScript()ed and then a contained function is called
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.getScript('myscript.js');
Hello();
</script>
I get:
ReferenceError: Hello is not defined
But if the script is referenced in an HTML <script> tag it works as expected
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">
Hello();
</script>
What I am missing? How to reference objects created in a getScript()ed script? The reason I want to use getScript() it to load the script on a ready() event.
The issue is that the $.getScript() function is asynchronous. When you call the Hello() function immediately after, the script is not yet loaded so the function is not available.
Loading scripts with regular <script> tags happens synchronously, so if you want to duplicate that behavior you have to disable the async option in your Ajax call.
getScript alone does not support this, so you can do this using an $.ajax call with the appropriate options:
$.ajax({
url: 'myscript.js',
dataType: 'script',
async: false
});
This will block the browser until the script is loaded.
However, a better technique is to use a callback, which $.getScript() does support:
$.getScript('myscript.js', function() {
Hello();
});
You need to wait for the response:
$.getScript('myscript.js', function(){
Hello();
});

Including JavaScript at runtime is not working in IE8

The below piece of code was working in IE6 & IE7 and almost all versions of FF. It just don't work in IE8. It doesn't work in the sense once I added the script tag in to HTML->HEAD element I don't see the script being loaded in the browser(the alerts in the script doesn't show up). I see the tags have been inserted in the HTML-HEAD though.
var head = document getElementsByTagName('head')[0];
// Check if the script is already loaded.
if (head ){
var script = document.createElement('script');
script.type = 'text/javascript';
script.language = 'JavaScript';
script.src = '/Tolven/scripts/' + jsFileName;
head.appendChild(script);
}
Does anybody have this issue? Or any clues to resolve this?
If this script is in <head> tag than head does not exists when this script is parsed and executed. So, of cource if (head) is false.
Your are using JS framework -- so feel free to use it's tools. And also do not forget to include Your framework, before using it.
<!-- if your are using mootools -->
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
window.addEvent('domready', function() {
// Your code...
});
</script>
<!-- if your are using prototype -->
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
document.observe("dom:loaded", function() {
// Your code...
});
</script>
Consider using a library like RequireJS or LABjs that do the job of including scripts at runtime really well.
var head = document getElementsByTagName('head')[0];
should be
var head = document.getElementsByTagName('head')[0];
Script seems to work after this modification.
This is was actually working. There is was an error(it only happens in IE8) in one of the scripts that's inserted at runtime. Eventually it's not executing alerts in the pages loaded next. Thanks for your answers though.

Categories