dojo using custom module from custom cdn source - javascript

we can use dojo toolkit after reference dojo script in our html page.
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js"></script>
<script type="text/javascript">
require(["dojo/dom"], function (dom) {
var button = dom.getById("ok");
});
</script>
we can use "dojo/dom" in our script.
I want to create my own javascript module in my server and use it everyvhere.
For example I have a domain http://mydomain.com/api/v1/app.js
I should use this app.js like this.
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js"></script>
<script src="//mydomain.com/api/v1/app.js"></script>
<script type="text/javascript">
require(["dojo/dom","app/something"], function (dom,something) {
var st = new something();
});
</script>
I created app.js file like this but did not work.
declare(["dojo/_base/declare"],
function (declare) {
return declare(null, {
constructor: function () {
console.log("hello");
}
});
})
How should I create my app.js file?

There are multiple issues here. The first one (and the real issue) is that Dojo will look relatively for your modules. This means that it will look somewhere on the CDN for your app module (which it obviously can't find).
To change the location of a package you have to configure the package section of the Dojo config. In your case that would be:
<script type="text/javascript">
dojoConfig = {
packages: [{
name: 'custom',
location: 'http://mydomain.com/api/v1/'
}]
}
</script>
Then you can get your module using:
require(["custom/app"], function(app) {
// Do something
});
Important: Make sure that the Dojo config is loaded before the Dojo loader (dojo.js). So you have to put this <script>-tag above the dojo.js script tag to make it work.
Another issue is that in app.js you have to use define() as the first statement and not declare(). For example:
define(["dojo/_base/declare"],
function (declare) {
return declare(null, {
constructor: function () {
console.log("hello");
}
});
})

Related

External javascript from public/index.html not loading in Vue component

I want to use Mathjax on my website. I put in the <head> section of public/index.html:
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js"></script>
And, in my component :
<template>
<div v-html="note_content"></div>
</template>
<script>
import { typeset, dummy_typeset } from '../assets/js/text_processing.js';
import showdown from 'showdown';
const converter = new showdown.Converter({ tables: true });
export default {
data () {
return {
}
},
computed: {
note_content: function() {
return typeset(this.exchange_data);
}
},
props: ['exchange_data'],
watch: {
note_content: function() {
Mathjax.typesetPromise();
}
}
}
</script>
However on runtime, I get the error :
Uncaught (in promise) ReferenceError: Mathjax is not defined
What I do not understand is that the css which is located in the head of public/index.html is correctly loaded and rendered in the component. Also I read elsewhere that loading external javascript this way should make it available to all components. What is wrong ?
I think it is connected to webpack config, but i might be wrong. Anyway, have you tried this method?
How to add external JS scripts to VueJS Components?
It enforces the script to be loaded.
Contrarily to what is written at https://docs.mathjax.org/en/latest/web/typeset.html, the syntax for asynchronous rendering is not :
Mathjax.typesetPromise()
But (notice the case):
MathJax.typesetPromise()
The typo could be detected from the surrounding context.
Also not that to use typeset Mathjax in a Vue component, the virtual DOM should be processed before calling the typesetPromise method, so an example of working code would be:
watch: {
note_content: function() {
this.$nextTick(MathJax.typesetPromise);
}
}

Send a PHP array to a JS Module, "import" problems

I'm making a website to learn PHP and Javascript/JQuery, i don't have much experience yet and i'm trying to understand what's the best structure to implement
PHP creates an array of strings
i can access the array from index.php via json_encode
then i want to send the array to a function in a class which is in a .mjs file
the problem is that in the index.php file, by the script tags i can't import the module, and if i use script type="module" i can use the import
but i get this error:
Failed to load module script: The server responded with a non-JavaScript MIME type of "" in main.mjs::1
the MDN reference the mjs extension is used to prevent that.
that's why i'm stuck.
server directory looks like this:
index.php
js/main.mjs
js/index.mjs
Code snippets:
index.php
<head>
<meta charset="utf-8">
<title>Website</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/jquery-3.4.1.slim.min.js"></script>
<script src="js/main.mjs" type="module"></script>
<script type="module">
import {start_index} from "./js/main.mjs";
initialize();
function initialize()
{
var arr = <?php echo json_encode($images_arr); ?>;
start_index(arr);
}
</script>
</head>
main.mjs
function start_index(arr)
{
import {gallery_manager} from './index.mjs';
var gallery_mngr = new gallery_manager();
gallery_mngr.initialize(arr);
}
export {start_index};
index.mjs
class gallery_manager
{
constructor(){}
var images = "";
var placeholder = "../images/common/placeholder.png";
public function initialize(arr)
{
images = arr;
alert(images[0]);
}
function switchByTimer()
{
}
function switchImage(new_image, direction)
{
}
}
export {gallery_manager};
MAIN PROBLEM:
Your web server doesn't appear to "understand" what an "mjs" file is, so it isn't sending the appropriate MIME type in the response's HTTP header.
SUGGESTION: change ".mjs" to "js" and see if that helps. "mjs" is oriented toward NodeJS.
IMPORTANT QUESTIONS:
Q: You're using a web server, correct?
Q: What kind of web servier? Apache2/Linux? IIS Express local Windows PC? Something else?
STRONG SUGGESTION: familiarize yourself with Chrome Developer Tools.
I've managed to fix my code, paulsm4 has lit a spark in my brain
.mjs extension strangely does not work, i have no idea why it's advised to use that extension for javascript modules as it is stated in the MDN reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
also, some of my JS code was broken, especially class variables and functions
because i'm still learning the syntax..
now it's working as supposed
index.php
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/jquery-3.4.1.slim.min.js"></script>
<script src="js/main.js" type="module"></script>
<script type="module">
import start_index from "./js/main.js";
initialize();
function initialize()
{
var arr = <?php echo json_encode($images_arr); ?>;
start_index(arr);
}
</script>
main.js
import gallery_manager from './index.js';
function start_index(arr)
{
var gallery_mngr = new gallery_manager(arr);
gallery_mngr.initialize();
}
export default start_index;
index.js
class gallery_manager
{
constructor(images, placeholder)
{
this.images = images;
this.placeholder = "../images/common/placeholder.png";
}
initialize()
{
alert(this.images[0]);
}
switchByTimer()
{
}
switchImage(new_image, direction)
{
}
}
export default gallery_manager;

External Javascript is not working in react.js

I am creating a react app using create-react-app. I have some external javascript libraries for template design in main index.html
<script src="%PUBLIC_URL%/js/jquery-2.2.4.min.js"></script>
<script src="%PUBLIC_URL%/js/common_scripts.js"></script>
<script src="%PUBLIC_URL%/js/main.js"></script>
<script src="%PUBLIC_URL%/js/owl.carousel.js"></script>
These JS files are working on first page when the application gets started. But these libraries are not working when redirect to other page from first page.
From what I understand, these files are rendering but their functions, variables, and methods are not accessible when the route is changed.
I am using react-router-dom v4 for routing .
I googled it and found a solution-
To render the JS libraries by ComponentDidMount() method
ComponentDidMount(){
loadjs('./js/main.js', function(){
loadjs('./js/common_scripts.js)
});
}
But even this solution is not working.
Please help to solve this issue.
Thanks
This is how i import Jquery into my create react app
Jquery:
first run npm install jquery
index.js
import * as $ from 'jquery'
window.jQuery = window.$ = $
see: http://blog.oddicles.org/create-react-app-importing-bootstrap-jquery-cleanly-node-js/
Alternativly you can attach the scripts to a window object and then call them as needed:
Try following steps:
including the external js file link in your /public/index.html
use the external library with prefix window.
for example, JQuery.
put following line in your /public/index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>`
use it in your project:
window.$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
`
See this for more details:
https://github.com/facebook/create-react-app/issues/3007
You are using componentWillMount() instead of componentDidMount().
I think that is the problem here.
You can set that js files on window object and then you can access it by window.your_name to object..
You have to set that in index file
Try using import() inside componentDidMount()
The import() is self explaining.It just import's the JavaScript files.
import('your_URL')
Try to call event using window object. reference Link
const loadScript = (src) => {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.src = src
script.addEventListener('load', function () {
resolve()
})
script.addEventListener('error', function (e) {
reject(e)
})
document.body.appendChild(script)
document.body.removeChild(script)
})
}
useEffect(() => {
loadScript(`${process.env.PUBLIC_URL}/js/plugin.min.js`)
setTimeout(() => {
setTimeout(() => {
setLoading(false)
}, 500)
loadScript(`${process.env.PUBLIC_URL}/js/main.js`)
}, 200)
}, [])

Unexpected token import on Electron app

I have built an app using GitHub's Electron. I am using the recommended way of loading modules, the ES6 syntax of:
import os from 'os'
After downloading the boilerplate the app is working fine. I have been able to import scripts in the background.js file without issue. Below is how I am loading my custom module:
import { loadDb } from './assets/scripts/database.js';
However, when I open a new browser window (clipboard.html) within Electron I am then loading a JavaScript file (clipboard.js) which in turn tries to import modules. At this point I am getting an Unexpected token import error.
My clipboard.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Electron Boilerplate</title>
<link href="./stylesheets/main.css" rel="stylesheet" type="text/css">
<script>
window.$ = window.jQuery = require('./assets/scripts/jquery-1.12.1.min.js');
</script>
<script src="./assets/scripts/clipboard.js"></script>
</head>
<body class="clipboard">[...]</body></html>
My clipboard.js file:
import { remote } from 'electron'; // native electron module
import { loadDb } from './assets/scripts/database.js';
const electron = require('electron');
document.addEventListener('DOMContentLoaded', function () {
var db = loadDb();
db.find({ type: 'text/plain' }, function (err, docs) {
var docsjson = JSON.stringify(docs);
console.log(docsjson);
});
});
Just to re-iterate, the same code is used within app.html, which is my app's main window, and this does not error.
It feels like the main window is initialising something that my clipboard.html window isn't (perhaps 'Rollup'?), but there's nothing explicit within my app's code to suggest this.
You need to run clipboard.js through rollup first. Rollup parses the import statements. You have to modify tasks/build/build.js to do that.
var bundleApplication = function () {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(srcDir.path('clipboard.js'), destDir.path('clipboard.js')), // Add this line
bundle(srcDir.path('app.js'), destDir.path('app.js')),
]);
};
#user104317 got it right, clipboard.js just didn't get "compiled" by rollup.
Just wanted to add that in your case, it should have been:
var bundleApplication = function () {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(srcDir.path('app.js'), destDir.path('app.js')),
bundle(srcDir.path('assets/scripts/clipboard.js'), destDir.path('assets/scripts/clipboard.js')),
]);
};
Then you could have left it at ./assets/scripts/clipboard.js.
If you end up having a lot of independent js files (you shouldn't if you're building a SPA), consider listing them automatically, like done in ./tasks/build/generate_spec_imports.js

Meteor: inject html into client-side file on startup

Using the SSR and inject initial packages,
I currently have the following server-side code:
Meteor.startup(function() {
.....
Inject.rawHead('importList', function(imports) {
return imports = Blaze.toHTML(Template.imports);
});
});
This injects a list of html imports into the head, and works perfectly.
I'd like to modify the function so that the code is injected into /client/imports.html instead of into the head... can this be done?
Looks close to this solution. Try this in the client folder of Meteor or use if(Meteor.isClient) for compactness:
Inject.rawHead('importList', function(imports){
return imports = Blaze.toHTML(Template.imports)
})
Meteor.startup(function(){
//...
})

Categories