I went to Pinboard's Resource page, got my widget and it all works beautifully. I've styled it up (sidebar on anwarchoukah.com) and am generally happy.
The code generated is
<script language="javascript"
src="http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5">
</script>
My problem is that I want to have the links open in a new window - any ideas?
P.S. I'm not very good with JavaScript
[edit] The second answer is not going to work because async. loaded scripts are not allowed to write into the document! But the first one is shorter as well, it will only fail when the request to pinboard.in is slower than 500ms.
Working answer
So you would go the timeout route and run the script when some time has passed to make sure the pinboard script has run and its response is accessible by getElementsByTagName. your <scripttag would remain as is, you will only have to add the following javascript code in your main .js file:
window.onload = function() {
setTimeout( function() {
var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
for ( var i = 0; i < anchors.length; i++ ) {
anchors[i].setAttribute( 'target', '_blank' );
}
}, 500 );
};
Not working answer left for reference
first you have to hijack the loading of the script. then you can modify the attr target in the callback function.
this javascript goes into wherever your main scripts are loaded:
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.getElementById( 'pinboard_hook' )[0].appendChild( script );
}
window.onload = function() {
loadScript( 'http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5', function() {
var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
for ( var i = 0; i < anchors.length; i++ ) {
anchors[i].setAttribute( 'target', '_blank' );
}
});
}
in your html you would replace the <script> tag with a simple wrapper like:
<span id="pinboard_hook"></span>
Related
I am trying to load the following script with Javascript:
function put() {
var group = document.getElementById("obj_0123456790");
var children = group.childNodes;
for( var i = 0; i < children.length; i++ ) {
if( (children[i].name == 'movie') || (children[i].name == '') ) {
children[i].src = "http://website.com/song.swf";
}
}
}
if (window.attachEvent) {
window.attachEvent('onload', put);
} else {
if (window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
put();
};
window.onload = newonload;
} else {
window.onload = put;
}
}
I load it with the following code:
<script>
var i=document.createElement('script');
i.src="http://website.com/putter.js";
document.head.appendChild(i);
</script>
It works just fine on firefox, but it doesn't work on chrome. How can I make it work on chrome?
1.This function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parent.insertBefore(s, t);
}
2.If you've already got jQuery on the page, just use
$.getScript(url, successCallback)
The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.
If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).
3.Example from Google
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
4.You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript
5.If its any help take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.
Here is an example of loading jquery:
Modernizr.load([
{
load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
complete: function () {
if ( !window.jQuery ) {
Modernizr.load('js/libs/jquery-1.6.1.min.js');
}
}
},
{
// This will wait for the fallback to load and
// execute if it needs to.
load: 'needs-jQuery.js'
}
]);
Inside a script file I have to dynamicaly import another script and use functions and variables defined inside of it.
Right now, I'm adding it to the HEAD section of the Page, but just after adding it, functions and variables defined inside the outer script are not loaded and ready for use yet. How can I do that and be sure that the script was fully loaded?
I've tried using script.onreadystatechange and script.onload callbacks but I'm having some browser compatibility issues.
How do I do that, as safely as possible, with pure JS and decent browser compatibility?
Sample:
uno.js:
var script = document.createElement("script");
script.src = "dos.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
alert(outerVariable); // undefined
dos.js:
var outerVariable = 'Done!';
sample.html
<html>
<head>
<script type="text/javascript" src="uno.js"></script>
</head>
...
</html>
If you are concerned with non-IE browsers I would try using DOMContentLoaded to see if the script is fully loaded.
You can see more about it here
In fact this is sort of how JQuery works with document ready. This is the snippit from the jquery source:
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
If you were to look at the jquery code to copy what they do it's in the bind ready function of the full source code.
So far, this seems to be the better working approach. Tested on IE9, Firefox and Chrome.
Any concerns?
uno.js:
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
if (navigator.appName=="Microsoft Internet Explorer") {
script.onreadystatechange = function(){
if (script.readyState == 'loaded') {
document.getElementsByTagName('head')[0].appendChild(script);
callback();
}
};
} else {
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function(){
callback();
};
}
}
loadScript('dos.js', function(){
alert(outerVariable); // "Done!"
});
use the onload (IE9-11,Chrome,FF) or onreadystatechange(IE6-9).
var oScript = document.getElementById("script")
oScript.src = "dos.js"
if (oScript.onload !== undefined) {
oScript.onload = function() {
alert('load')
}
} else if (oScript.onreadystatechange !== undefined) {
oScript.onreadystatechange = function() {
alert('load2')
}
}
I have a static page that I'm trying to add jQuery and the BlockUI plugin to. jQuery needs to be loaded first before I can use BlockUI, and while I can load jQuery just fine, I cant seem to get BlockUI to load after and call its loaded handler so I can do the work. I do see the BlockUI script tag in my html page, so it is at least being injected in okay as far as I can see. Here's my code:
var jqueryScript = document.createElement( "script" );
jqueryScript.src = "/glptools/scripts/jquery-1.9.1.min.js";
if ( jqueryScript.addEventListener ) {
jqueryScript.addEventListener( "load", jqueryReady, false );
}
else if ( jqueryScript.readyState ) {
jqueryScript.onreadystatechange = jqueryReady;
}
document.getElementsByTagName( 'head' )[0].appendChild( jqueryScript );
function jqueryReady() {
if ( typeof jQuery != 'undefined' ) {
$( document ).ready( function () {
//Initialize Tabber
tabberAutomatic( "" );
// Add BlockUI plugin
var blockUIScript = document.createElement( "script" );
blockUIScript.src = "/glptools/scripts/blockui/jquery.blockUI.js";
if ( blockUIScript.addEventListener ) {
blockUIScript.addEventListener( "load", blockUIReady, false );
}
else if ( blockUIScript.readyState ) {
blockUIScript.onreadystatechange = blockUIReady;
}
document.getElementsByTagName( 'head' )[0].appendChild( blockUIScript );
} );
}
}
function blockUIReady() {
$( "#tabbertabhide" ).each( function ( index, elem ) {
$( elem ).block();
} );
}
My goal is to use BlockUI to block the tabs located on my page. I tried putting the block ui load code outside the ready() call, but then the loaded handler gets called before jQuery has been loaded.
You should consider use of script loader such as http://requirejs.org/ or http://headjs.com/ which can resolve dependecies tree for you and make code cleaner.
If BlockUI depends on jQuery, you will need to load it sequentially. You can do something like this:
//This function creates a script element using "resource" and
//adds it to the head. callback is used as the onload callback
//for the script
function loadScript(resource, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = resource + "?t=" + new Date().getTime(); //prevent caching
if (callback) {
script.onload = callback;
}
head.appendChild(script);
}
//Array of scripts to load
var resources = [
"/glptools/scripts/jquery-1.9.1.min.js",
"/glptools/scripts/blockui/jquery.blockUI.js"
];
//This function will load the scripts one after the other, using a callback
//that calls this function itself.
function load(i) {
if(i < resources.length) {
loadResource(resources[i], function() {
load(++i);
});
} else {
//Everything has finished loading so you can start
//using jQuery and BlockUI
}
}
load(0);
As far as both jQuery and BlockUI are located in the same origin as your page you can get jQuery and BlockUI scripts as text, concat them and add to document as merged script. Just like this:
function createXMLHttp() {
//Initializing our object
var xmlHttp = null;
//if XMLHttpRequest is available then creating and returning it
if (typeof(XMLHttpRequest) != undefined) {
xmlHttp = new XMLHttpRequest;
return xmlHttp;
//if window.ActiveXObject is available than the user is using IE...so we have to create the newest version XMLHttp object
} else if (window.ActiveXObject) {
var ieXMLHttpVersions = ['MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp', 'Microsoft.XMLHttp'];
//In this array we are starting from the first element (newest version) and trying to create it. If there is an
//exception thrown we are handling it (and doing nothing)
for (var i = 0; i < ieXMLHttpVersions.length; i++) {
try {
xmlHttp = new ActiveXObject(ieXMLHttpVersions[i]);
return xmlHttp;
} catch (e) {
}
}
}
}
function getData(url, callback) {
var xmlHttp = createXMLHttp();
xmlHttp.open('get', url, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
callback(xmlHttp.responseText);
}
}
};
}
getData('/glptools/scripts/jquery-1.9.1.min.js', function(jQuery) {
getData('/glptools/scripts/blockui/jquery.blockUI.js', function(blockUi) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement('script');
script.innerHTML = jQuery + ';' + blockUi;
head.appendChild(script);
});
});
I've been working on a bookmarklet project that loads external jQuery.js file like this:
jq_script = document.createElement('SCRIPT');
jq_script.type = 'text/javascript';
jq_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq_script);
But when I try use jQuery right after this, I receive:
Uncaught ReferenceError: jQuery is not defined
on the chrome JS console.
Is there any "event" that is called when a single DOM instance is loaded?
(or any event that gets triggered when an external JS file is loaded like this?)
<script> elements have an onload event.
You can do like this
function loadScript()
{
jq_script = document.createElement('SCRIPT');
jq_script.type = 'text/javascript';
jq_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq_script);
}
window.onload = loadScript;
Update : Using latest jquery code below.
jQuery's getScript handles it in the below way. You can place your functionality inside if(!isAbort).
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
//**Do your stuff here**
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
I am trying to load a css file dynamically using javascript and cannot use any other js library (eg jQuery).
The css file loads but I can't seem to get a callback to work for it. Below is the code I am using
var callbackFunc = function(){
console.log('file loaded');
};
var head = document.getElementsByTagName( "head" )[0];
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", url);
fileref.onload = callbackFunc;
head.insertBefore( fileref, head.firstChild );
Using the following code to add a script tag to load a js file works and fires a callback:
var callbackFunc = function(){
console.log('file loaded');
};
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
script.onload = callbackFunc ;
head.insertBefore( script, head.firstChild );
Am I doing something wrong here? Any other method that can help me achieve this would be much appreciated?
Unfortunately there is no onload support for stylesheets in most modern browsers. There is a solution I found with a little Googling.
Cited from: http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof
The basics
The most basic implementation of this can be done in a measely 30 lines of — framework independent — JavaScript code:
function loadStyleSheet( path, fn, scope ) {
var head = document.getElementsByTagName( 'head' )[0], // reference to document.head for appending/ removing link nodes
link = document.createElement( 'link' ); // create the link node
link.setAttribute( 'href', path );
link.setAttribute( 'rel', 'stylesheet' );
link.setAttribute( 'type', 'text/css' );
var sheet, cssRules;
// get the correct properties to check for depending on the browser
if ( 'sheet' in link ) {
sheet = 'sheet'; cssRules = 'cssRules';
}
else {
sheet = 'styleSheet'; cssRules = 'rules';
}
var interval_id = setInterval( function() { // start checking whether the style sheet has successfully loaded
try {
if ( link[sheet] && link[sheet][cssRules].length ) { // SUCCESS! our style sheet has loaded
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
fn.call( scope || window, true, link ); // fire the callback with success == true
}
} catch( e ) {} finally {}
}, 10 ), // how often to check if the stylesheet is loaded
timeout_id = setTimeout( function() { // start counting down till fail
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
head.removeChild( link ); // since the style sheet didn't load, remove the link node from the DOM
fn.call( scope || window, false, link ); // fire the callback with success == false
}, 15000 ); // how long to wait before failing
head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet
return link; // return the link node;
}
This would allow you to load a style sheet with an onload callback function like this:
loadStyleSheet( '/path/to/my/stylesheet.css', function( success, link ) {
if ( success ) {
// code to execute if the style sheet was loaded successfully
}
else {
// code to execute if the style sheet failed to successfully
}
} );
Or if you want to your callback to maintain its scope/ context, you could do something kind of like this:
loadStyleSheet( '/path/to/my/stylesheet.css', this.onComplete, this );
This vanilla JS approach works in all modern browsers:
let loadStyle = function(url) {
return new Promise((resolve, reject) => {
let link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.onload = () => { resolve(); console.log('style has loaded'); };
link.href = url;
let headScript = document.querySelector('script');
headScript.parentNode.insertBefore(link, headScript);
});
};
// works in IE 10, 11 and Safari/Chrome/Firefox/Edge
// add an ES6 polyfill for the Promise (or rewrite to use a callback)
Some time ago i made a library for this, it's called Dysel, i hope it helps
Example:
https://jsfiddle.net/sunrising/qk0ybtnb/
var googleFont = 'https://fonts.googleapis.com/css?family=Lobster';
var jquery = 'https://code.jquery.com/jquery.js';
var bootstrapCss = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css';
var bootstrapJs = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js';
var smokeCss = 'https://rawgit.com/alfredobarron/smoke/master/dist/css/smoke.min.css';
var smokeJs = 'https://rawgit.com/alfredobarron/smoke/master/dist/js/smoke.min.js';
// push links into an array in the correct order
var extRes = [];
extRes.push(googleFont);
extRes.push(bootstrapCss);
extRes.push(smokeCss);
extRes.push(jquery);
extRes.push(bootstrapJs);
extRes.push(smokeJs);
// let this happen
dysel({
links: extRes,
callback: function() {
alert('everything is now loaded, this is awesome!');
}, // optional
nocache: false, // optional
debug: false // optional
});
You can make an empty css link in your html file and give the link an ID. e.g
<link id="stylesheet_css" rel="stylesheet" type="text/css" href="css/dummy.css?"/>
then call it with ID name and change the 'href' attribute
yepnope.js can load CSS and run a callback on completion. e.g.
yepnope([{
load: "styles.css",
complete: function() {
console.log("oooooo. shiny!");
}
}]);
Here's how we do it. By using "requestAnimationFrame" (or fallback to simple "load" event if its not avail).
By the way, this is the way Google recommends in their "page-speed" manual:
https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
<script>
function LoadCssFile(cssPath) {
var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = cssPath;
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
}
var cb = function() {
LoadCssFile('file1.css');
LoadCssFile('file2.css');
};
var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
New answer to an old question:
You can simply request the text of the CSS file with AJAX and put it in a <style> tag. When the styles have been appended to the DOM they are available immediately.
Here's a script I came up with:
/**
* Given a URL for a JS or CSS file, this function will
* load the asset and return a Promise which will reject
* on error or resolve when the asset is loaded.
*/
function loadAsset(url){
return new Promise(async (resolve, reject)=>{
var asset;
if(url.trim().substr(-3).toLowerCase() === '.js'){
asset = document.createElement('script');
asset.addEventListener('load', resolve);
asset.addEventListener('error', reject);
document.head.appendChild(asset);
asset.setAttribute('src', url);
}else{
var styles = await fetch(url)
.then(c=>c.text())
.catch(reject);
asset = document.createElement('style');
asset.appendChild(document.createTextNode(styles));
document.head.appendChild(asset);
resolve();
}
});
}