Load an external JS file from a JS class - javascript

I use an external js file on my site, it currently sits at the bottom of my boilerplate.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
I only need to load this script on specific pages or when a specific modal loads.
Is there a way to call the script from my javascript code. For example:
$(document).one('opened.fndtn.reveal', '#my-modal[data-reveal]', function () {
//load places api
});
Also Google suggest having it on every page - why is this? I do not need to use it on every page.

You can use .getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript("https://maps.googleapis.com/maps/api/js?libraries=places", function(){
alert("script loaded");
});

Another way if you don't have jQuery.
function inyectScript(url, success){
var script = document.createElement('script');
script.src = url;
script.id = "myScript";
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
}
};
document.getElementsByTagName('head')[0].appendChild(script);
}

Related

Listen to see if content from external js file is loaded in DOM for javascript to use

I'm trying to run javascript on a form that is loaded in content coming from an external js file, but it's failing because content doesn't load right away
I've tried listening for the load of the html button in the iframe, but not getting anything:
document.querySelector('#hyform button').addEventListener('load', function() {
console.log('external js content loaded');
}
UPDATED QUESTION. This is not an iframe but content loaded from an external js file. I dont have control of the external js file.
You can dynamically append the file to <head>, then monitor the load state:
var callback = function () {
// do stuff
};
var script = document.createElement('script');
script.src = 'path_to_file.js'
script.type = 'text/javascript';
if (script.readyState) {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
callback();
script.onreadystatechange = null;
}
} else {
script.onload = function () {
callback();
};
}
document.getElementsByTagName("head")[0].appendChild(script);

Cannot call function from dynamically loaded javascript file

I'm loading a javascript external file from another javascript file present in the document and since its loaded, I want to call a function from the loaded js file.
Here is the load function:
function loadScript(url) {
var head = window.top.document.getElementsByTagName('head')[0];
var script = window.top.document.createElement('script');
script.src = url;
script.type= "text/javascript";
head.appendChild(script);
if(script.readyState) { //IE
script.onreadystatechange = function() {
if ( script.readyState === "loaded" || script.readyState === "complete" ) {
script.onreadystatechange = null;
console.log("[BANDEAU] script loaded");
testAlert();
}
};
} else { //Others
script.onload = function() {
console.log("[BANDEAU] script loaded");
testAlert();
};
}
}
So it works nice because the javascript file is succesfuly loaded but I cannot access the testAlert() method from the loaded javascript file, as I try in the code above, right after printing that the script is loaded. When I try to get the type of the function with typeOf on window[testAlert], I get an undefined. But when I try to execute the testAlert() method in the developer console, it works perfectly. Does anyone see what I'm doing wrong ?
Does the position in the DOM between the caller javascript file and the loaded javascript file might be the reason ?
You need to assign the load handlers BEFORE changing the src
function loadScript(url) {
var head = document.getElementsByTagName('head')[0]; // window.top in frames/iFrames
var script = document.createElement('script');
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
console.log("[BANDEAU] script loaded");
testAlert(); // window.top.testAlert() if needed
}
};
}
else {
script.onload = function() {
console.log("[BANDEAU] script loaded");
testAlert(); // window.top.testAlert() if needed
};
}
script.src = url;
head.appendChild(script);
}
In addition to what mplungjan said, I'm pretty sure you'd have to do an eval() on the loaded script in order to have a legitimate address for the call to testAlert().
Also, check out this link for more info.

wait for scripts to load that have been added through javascript

I need to add jquery and then another script that relies on jquery.
I then need to have code that uses both assets but my problem is that i don't want my code to run until i know that both assets are loaded.
I think the process would be to load jquery and then wait until jquery is loaded by waiting for window.onload, then load the jquery plugin, then detect that the plugin has loaded, then load my own code that uses functions from the jquery plugin.
code so far:
// load jquery if it is not allready loaded and put it into no conflict mode so the $ is available for other librarys that might be allready on the page.
if(!window.jQuery) {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict(); // stop jquery eating the $
console.log("added jquery");
}
window.onload = function(e) {
// we know that jquery should be available now as the window has loaded
if ( !jQuery.isFunction(jQuery.fn.serializeObject) ) { // use jquery to ask if the plugins function is allready on the page (don't do this if the website already had the plugin)
// website didn't have the plugin so add it to the page.
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
if ( !jQuery.isFunction(jQuery.fn.serializeObject) ) {
// console.log("serializeObject is undefined");
// its going to be undefined here because Its still loading in the script
} else {
// console.log("we have serializeObject");
}
// I now dont know when to call my code that uses .serializeObject() because it could still be loading
// my code
var form_data_object = jQuery('form#mc-embedded-subscribe-form').serializeObject();
};
You have to do like
Include
<script type="text/javascript" id="AssetJS"></script>
Script
$("#AssetJS").attr("src", "Asset.js");
$("#AssetJS").load(function () {
//after loaded jquery asset do your code here
})
OK i managed to find another way that is working for my specific needs so I am answering my own question.
Using this function from http://www.sitepoint.com/dynamically-load-jquery-library-javascript/
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
and usage in my case:
if(!window.jQuery) {
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js", function () {
jQuery.noConflict(); // stop jquery eating the $
console.log('jquery loaded');
if ( !jQuery.isFunction(jQuery.fn.serializeObject) ) { // use jquery to ask if the plugins function is already on the page
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js", function () {
console.log('serialize loaded');
SURGE_start(); // both scrips where not on the website but have now been added so lets run my code now.
});
}
});
} else {
if ( !jQuery.isFunction(jQuery.fn.serializeObject) ) { // use jquery to ask if the plugins function is already on the page
loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js", function () {
console.log('serialize loaded');
SURGE_start(); // jquery was on the web page but the plugin was not included. now we have both scripts lets run my code.
});
} else {
SURGE_start(); // web page already had both scripts so just run my code.
}
}
An easy way is using headjs. It's working fine on several projects.

How to embed Javascript widget that depends on jQuery into an unknown environment

I'm developing a javascript widget that depends on jQuery. The widget may or may not be loaded onto a page that already has jQuery loaded. There are many problems that come up in this case...
If the web page does not have jQuery, I must load my own jQuery. There seems to be a delicate timing issue when doing this, however. For example, if my widget loads and executes before jQuery is finished loading and executing, I get a jQuery is not defined error.
If the web page does have jQuery, I can usually work with it. If the jQuery version is old, however, I would like to load my own. If I do load my own, however, I need to do it in such a way as to not stomp on their $ variable. If I set jQuery.noConflict() and any of their scripts depend on $, then I have just broken their page.
If the web page uses another javascript library (e.g. prototype), I needed to be sensitive of prototype's $ variable also.
Because of all of the above, it is seeming easier to not depend on jQuery. But before I go down that road, which will involve mostly rewriting my widget code, I wanted to ask for advice first.
The basic skeleton of my code, including the timing bug and sometimes $ bugs, follows:
<script type="text/javascript" charset="utf-8">
// <![CDATA
if (typeof jQuery === 'undefined') {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '{{ URL }}/jquery.js';
head.appendChild(script);
}
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>
My widget has the following structure:
(function($) {
var mywidget = {
init: function() {
...
}
};
$(document).ready(function() {
mywidget.init();
});
})(jQuery);
If there are any pointers or resources for achieving a widget that can work in all the mentioned environments, they would be greatly appreciated.
After reviewing some answers and pointers, and finding some helpful jQuery hackers, I ended up with something like the following:
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "/media/jquery.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
}
})(window, document, "1.3", function($, jquery_loaded) {
// Widget code here
});
This will load jQuery if it's not already loaded and encapsulates it in the callback so it doesn't conflict with a pre-existing jQuery on the page. It also checks that a minimum version is available or else loads a known version -- in this case, v1.3. It sends a boolean value to the callback (my widget) on whether or not jQuery was loaded in case there are any triggers needed to be made. And only after jQuery is loaded does it call my widget, passing jQuery into it.
See How to build a web widget (using jQuery) by Alex Marandon.
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
// We can use jQuery 1.4.2 here
});
}
})(); // We call our anonymous function immediately
What if you also want to use some jQuery plugins? Is it safe to make yourself a single file with the minified versions of the plugins, and also load those, as below? (Loaded from S3, in this particular example.)
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
window.jQuery.getScript('http://mydomain.s3.amazonaws.com/assets/jquery-plugins.js', function() {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
});
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.5.2", function($, jquery_loaded) {
// widget code goes here
});
SEE Can I use multiple versions of jQuery on the same page?
Can you use document.write() to optionally add the jQuery script to the page? That should force jQuery to load synchronously. Try this:
<script type="text/javascript" charset="utf-8">
// <![CDATA
if (typeof jQuery === 'undefined') {
document.write('<script src="{{ URL }}/jquery.js"><' + '/script>');
}
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>
If you want to do the jQuery check inside your widget script then I believe the following works cross-browser:
(function() {
function your_call($) {
// your widget code goes here
}
if (typeof jQuery !== 'undefined') your_call(jQuery);
else {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '{{ URL }}/jquery.js';
var onload = function() {
if (!script.readyState || script.readyState === "complete") your_call(jQuery);
}
if ("onreadystatechange" in script) script.onreadystatechange = onload;
else script.onload = onload;
head.appendChild(script);
}
})()
I know this is an old topic... but i got something faster that your hack.
Try in your widget
"init": function()
that will fix the trouble
I would download the jQuery source and modify the jQuery object to another (jQueryCustom).
And then find the instance that sets the $ symbol as a jQuery object and comment that routine.
I don't know how easy or difficult could that be, but I'd sure give it a try.
(Also, check your second option, as it is not bad, the site where the widget will be executing, might have a jQuery version older than the one you need).
EDIT: I just checked the source. You just have to replace jQuery with another string (jQcustom for example). Then, try commenting this line:
_$ = window.$
And you make reference to the custom jQuery like this:
jQcustom("#id").attr(...)

Bookmarklet wait until Javascript is loaded

I've got a bookmarklet which loads jQuery and some other js libraries.
How do I:
Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: a metatag)
Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this post)
What's the simplest solution, cleanest resolution to these issues?
It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.
EDIT: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
// Usage:
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("https://code.jquery.com/jquery-latest.js", function()
{
$('my_element').hide();
});
To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).
To prevent the files from being cached, you can append a meaningless query string...
url = 'jquery.js?x=' + new Date().getTime();
I've paid an attention that in Chrome the order of scripts that are loaded is undetermined, when using #Vincent Robert's technique. In this case a little modification helps:
(function() {
var callback = function() {
// Do you work
};
// check for our library existence
if (typeof (MyLib) == 'undefined') {
var sources = [
'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
'http://myhost.com/javascripts/mylib.min.js'];
var loadNextScript = function() {
if (sources.length > 0) {
var script = document.createElement('script');
script.src = sources.shift();
document.body.appendChild(script);
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done
&& (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
loadNextScript();
}
}
} else {
callback();
}
}
loadNextScript();
} else {
callback();
}
})();
I got a little closer with this, but not completely. It would be nice to have a discrete, example of a bookmarklet that demonstrated how to avoided caching.

Categories

Resources